Skip to main content
 首页 » 编程设计

python之json_normalize 后的 Pandas 合并列

2024年10月01日8youxin

我在单列中有一个字典列表,但对于每一行,不同的 post_id 在单独的列中。我已经通过 pd.concat(json_normalize(d) for d in data['comments']) 获得了我正在寻找的数据框,但我想从原始数据中添加另一列附加原始 post_id 的数据框。

原创

'post_id' 'comments' 
 123456    [{'from':'Bob','present':True}, {'from':'Jon', 'present':False}] 

当前结果(在json_normalize之后)

comments.from    comments.present 
Bob              True 
Jon              False 

期望的结果

comments.from    comments.present    post_id 
Bob              True                123456 
Jon              False               123456 

感谢您的帮助

请您参考如下方法:

考虑首先输出数据帧 to_json 然后运行 ​​json_normalize :

import json 
from pandas import DataFrame 
from pandas.io.json import json_normalize 
 
df = DataFrame({'post_id':123456, 
                'comments': [{'from':'Bob','present':True},  
                             {'from':'Jon', 'present':False}]})     
df_json = df.to_json(orient='records') 
 
finaldf = json_normalize(json.loads(df_json), meta=['post_id'])     
print(finaldf) 
 
#   comments.from comments.present  post_id 
# 0           Bob             True   123456 
# 1           Jon            False   123456