将 pandas 数据帧单元格中的字典解析为新的行单元格(新列) [英] parsing a dictionary in a pandas dataframe cell into new row cells (new columns)
本文介绍了将 pandas 数据帧单元格中的字典解析为新的行单元格(新列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Pandas 数据框,其中包含一列包含包含键值对字典的单元格,如下所示:
I have a Pandas Dataframe that contains one column containing cells containing a dictionary of key:value pairs, like this:
{"name":"Test Thorton","company":"Test Group","address":"10850 Test #325\r\n","city":"Test City","state_province":"CA","postal_code":"95670","country":"USA","email_address":"test@testtest.com","phone_number":"999-888-3333","equipment_description":"I'm a big red truck\r\n\r\nRSN# 0000","response_desired":"week","response_method":"email"}
我正在尝试解析字典,因此生成的 Dataframe 包含每个键的新列,并且该行填充了每列的结果值,如下所示:
I'm trying to parse the dictionary, so the resulting Dataframe contains a new column for each key and the row is populated with the resulting values for each column, like this:
//Before
1 2 3 4 5
a b c d {6:y, 7:v}
//After
1 2 3 4 5 6 7
a b c d {6:y, 7:v} y v
非常感谢建议.
推荐答案
考虑 df
df = pd.DataFrame([
['a', 'b', 'c', 'd', dict(F='y', G='v')],
['a', 'b', 'c', 'd', dict(F='y', G='v')],
], columns=list('ABCDE'))
df
A B C D E
0 a b c d {'F': 'y', 'G': 'v'}
1 a b c d {'F': 'y', 'G': 'v'}
<小时>
选项 1
使用 pd.Series.apply
,就地分配新列
df.E.apply(pd.Series)
F G
0 y v
1 y v
这样分配
df[['F', 'G']] = df.E.apply(pd.Series)
df.drop('E', axis=1)
A B C D F G
0 a b c d y v
1 a b c d y v
<小时>
选项 2
使用 pd.DataFrame.assign
方法
df.drop('E', 1).assign(**pd.DataFrame(df.E.values.tolist()))
A B C D F G
0 a b c d y v
1 a b c d y v
这篇关于将 pandas 数据帧单元格中的字典解析为新的行单元格(新列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文