我有一个将数据帧转换为字典并将字典返回到相同数据帧格式的用例。我能够弄清楚如何将数据帧转换为我想要的字典所需的格式。但反之亦然,我陷入困境。
>>> df
C1 C2 C3
0 foo H C
1 foo D E
2 bar F G
3 bar E E
4 foo F G
>>> df['temp'] = df[['C2','C3']].apply(lambda x: {x[0]:x[1]},axis=1)
>>> df
C1 C2 C3 temp
0 foo H C {u'H': u'C'}
1 foo D E {u'D': u'E'}
2 bar F G {u'F': u'G'}
3 bar E E {u'E': u'E'}
4 foo F G {u'F': u'G'}
>>> df.groupby('C1')['temp'].apply(list)
C1
bar [{u'F': u'G'}, {u'E': u'E'}]
foo [{u'H': u'C'}, {u'D': u'E'}, {u'F': u'G'}]
Name: temp, dtype: object
>>> df.groupby('C1')['temp'].apply(list).to_dict()
{'foo': [{'H': 'C'}, {'D': 'E'}, {'F': 'G'}], 'bar': [{'F': 'G'}, {'E': 'E'}]}
在处理之后,我会得到类似的字典和值的变化很小。所以我想重新构建数据框。
当我重建时,
>>>pd.series({'foo': [{'H': 'C'}, {'D': 'E'}, {'F': 'G'}],
'bar': [{'F': 'G'}, {'E': 'E'}]})
bar [{u'F': u'G'}, {u'E': u'E'}]
foo [{u'H': u'C'}, {u'D': u'E'}, {u'F': u'G'}]
dtype: object
此后我不知道......
答案 0 :(得分:1)
df_dict = df.groupby('C1')[['C2', 'C3']].apply(lambda x: {k:v for k, v in x.to_records(index=False) for l in x}).to_dict()
{'foo': {'D': 'E', 'F': 'G', 'H': 'C'}, 'bar': {'E': 'E', 'F': 'G'}}
new_df = pd.DataFrame()
for k, v in df_dict.items():
for v1, v2 in v.items():
new_df = pd.concat([new_df, pd.DataFrame(columns=[k], data=[v1, v2], index=['C2', 'C3'])], axis=1)
print(new_df.T.reset_index().rename(columns={'index':'C1'}))
C1 C2 C3
0 bar F G
1 bar E E
2 foo F G
3 foo D E
4 foo H C
答案 1 :(得分:1)
这是你想要的吗?
dict = {'foo': [{'H': 'C'}, {'D': 'E'}, {'F': 'G'}], 'bar': [{'F': 'G'}, {'E': 'E'}]}
count = 0
for k,v in dict.items():
for ele in v:
for key, val in ele.items():
print(count, k, "\t", key, "\t", val)
count += 1
示例输出:
0 bar F G
1 bar E E
2 foo H C
3 foo D E
4 foo F G
答案 2 :(得分:1)
根据您修改后的字典d
,您可以使用列表推导来重新生成新的数据帧。
df_col_names = df.columns[:3] # Use the first three column names to match output.
>>> pd.DataFrame([(c1, sub_dict.keys()[0], sub_dict.values()[0])
for c1 in d.keys()
for sub_dict in d[c1]],
columns=df_col_names)
C1 C2 C3
0 foo H C
1 foo D E
2 foo F G
3 bar F G
4 bar E E