gpt4 book ai didi

python - Pandas 解析列中的 json 并扩展到数据框中的新行

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:06 26 4
gpt4 key购买 nike

我有一个包含(记录格式)json 字符串的数据框,如下所示:

In[9]: pd.DataFrame( {'col1': ['A','B'], 'col2': ['[{"t":"05:15","v":"20.0"}, {"t":"05:20","v":"25.0"}]', 
'[{"t":"05:15","v":"10.0"}, {"t":"05:20","v":"15.0"}]']})

Out[9]:
col1 col2
0 A [{"t":"05:15","v":"20.0"}, {"t":"05:20","v":"2...
1 B [{"t":"05:15","v":"10.0"}, {"t":"05:20","v":"1...

我想提取 json 并为每条记录向数据框添加一个新行:

    co1 t           v
0 A 05:15:00 20
1 A 05:20:00 25
2 B 05:15:00 10
3 B 05:20:00 15

我一直在试验以下代码:

def json_to_df(x):
df2 = pd.read_json(x.col2)
return df2

df.apply(json_to_df, axis=1)

但是生成的数据帧被分配为元组,而不是创建新行。有什么建议吗?

最佳答案

apply 的问题在于您需要返回多行,而它只期望返回一行。可能的解决方案:

def json_to_df(row):
_, row = row
df_json = pd.read_json(row.col2)
col1 = pd.Series([row.col1]*len(df_json), name='col1')
return pd.concat([col1,df_json],axis=1)
df = map(json_to_df, df.iterrows()) #returns a list of dataframes
df = reduce(lambda x,y:x.append(y), x) #glues them together
df

col1 t v
0 A 05:15 20
1 A 05:20 25
0 B 05:15 10
1 B 05:20 15

关于python - Pandas 解析列中的 json 并扩展到数据框中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32481961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com