Python 在数据帧内的单元格中获取值数组
更新:我重新措辞和思考了这个问题,我认为这样问这个问题更好。 所以我一直在做这件事,运气不好。下面是我想做的一个例子 我从一个数据帧开始:Python 在数据帧内的单元格中获取值数组,python,r,json,data-manipulation,Python,R,Json,Data Manipulation,更新:我重新措辞和思考了这个问题,我认为这样问这个问题更好。 所以我一直在做这件事,运气不好。下面是我想做的一个例子 我从一个数据帧开始: df = data.frame("one" = c(1,11), "two" = c(2,22), "three" = c(3,33)) one two three 1 2 3 11 22 33 我试图将上述情况转化为: one new 1 c(2,3) 11 c(22,33) 我已经尝试了一些事情,比如嵌套两列,
df = data.frame("one" = c(1,11), "two" = c(2,22), "three" = c(3,33))
one two three
1 2 3
11 22 33
我试图将上述情况转化为:
one new
1 c(2,3)
11 c(22,33)
我已经尝试了一些事情,比如嵌套两列,并试图映射到它们上面,等等。也许有一些简单的事情我在这里没有看到。我更愿意通过tidyverse在R中这样做,但在这一点上,我对任何事情都持开放态度
必须这样做,因为当它转换为JSON时,“new”下的值需要采用[1,2,3]&[11,22,33]的形式。也许用Python更容易些
我在R中使用jsonlite包来转换JSON
谢谢你的帮助。我想这应该只是一个
地图
练习:
df$new <- Map(c, df$two, df$three)
df
# one two three new
#1 1 2 3 2, 3
#2 11 22 33 22, 33
library(jsonlite)
toJSON(df[c("one","new")])
#[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}]
如果您喜欢tidyverse,您可以按如下方式使用它:
在python中,使用
pandas
:
import pandas as pd
df = pd.DataFrame([[1,2,3],[11,22,33]], columns=["one", "two","three"])
one two three
0 1 2 3
1 11 22 33
df['new'] = list(zip(df.two, df.three))
df[['one','new']].to_json(orient='records')
# '[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}]'
在R中,您可以使用
tidyr::nest()
toJSON()
:
@最近的邮件,谢谢你的回复。。我编辑了这个问题。。希望现在更清楚了。
map2(df$two, df$three, c)
import pandas as pd
df = pd.DataFrame([[1,2,3],[11,22,33]], columns=["one", "two","three"])
one two three
0 1 2 3
1 11 22 33
df['new'] = list(zip(df.two, df.three))
df[['one','new']].to_json(orient='records')
# '[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}]'
library(dplyr)
nest_df <- df %>%
group_by(one) %>%
tidyr::nest(c(two, three), .key="new")
# # A tibble: 2 x 2
# one new
# <dbl> <list>
# 1 1 <tibble [1 x 2]>
# 2 11 <tibble [1 x 2]>
nest_df[1, ][[2]]
# # A tibble: 1 x 2
# two three
# <dbl> <dbl>
# 1 2 3
df %>%
group_by(one) %>%
tidyr::nest(c(two, three), .key="new") %>%
jsonlite::toJSON()
#[{"one":1,"new":[{"two":2,"three":3}]},{"one":11,"new":[{"two":22,"three":33}]}]