我正在尝试从 pandas 数据帧生成字典。具体来说,我需要:
选取前 (x) 列,并将每行中的数据点一起用作键。
使用行中剩余的数据点作为值(作为列表)为每个键编译字典。
为了简单起见,让我们使用这个示例数据框。
- 生成数据框:
df = pd.DataFrame([
{'c1':a1, 'c2':110, 'c3':'xyz', 'c4':24},
{'c1':b2,'c2':100, 'c3':'jdf', 'c4':15},
{'c1':a1,'c2':110, 'c3':'kjl', 'c4':125},
{'c1':b2, 'c2':100, 'c3':'abc', 'c4':71},
])
c1 c2 c3 c4
0 a1 110 xyz 24
1 b2 100 jdf 15
2 a1 110 kjl 125
3 b2 100 abc 71
- 产生以下结果:
new_dict = some code
new_dict
{('a1', 110): [['xyz', 24], ['kjl', 125]], ('b2', 100): [['jdf', 15], ['abc', 71]]}
我已经尝试了很多很多事情,包括为键创建元组列表的列表,将唯一列表分配为新字典的键(值为空列表) - 但我无法填充这些值。
我可以编译一个以单列为键的字典,并根据需要编写其他所有内容,如下所示:
test_dict = {}
for index, row in df.iterrows():
if row['c1'] in test_dict:
test_dict[row['c1']].append([row['c2'], row['c3'], row['c4']])
else:
test_dict[row['c1']] = []
test_dict[row['c1']].append([row['c2'], row['c3'], row['c4']])
但我无法跳转到组合多个列作为键。
最佳答案
假设以下数据帧:
import pandas as pd
df = pd.DataFrame([
{'c1': 'a1', 'c2': 110, 'c3': 'xyz', 'c4': 24},
{'c1': 'b2', 'c2': 100, 'c3': 'jdf', 'c4': 15},
{'c1': 'a1', 'c2': 110, 'c3': 'kjl', 'c4': 125},
{'c1': 'b2', 'c2': 100, 'c3': 'abc', 'c4': 71},
])
你可以groupby ,聚合然后转换为字典( to_dict ):
groups = df.groupby(['c1', 'c2']).apply(lambda x: x[['c3', 'c4']].values.tolist()).to_dict()
print(groups)
输出
{('a1', 110): [['xyz', 24], ['kjl', 125]], ('b2', 100): [['jdf', 15], ['abc', 71]]}
关于python - 从 pandas 数据帧生成字典,其中多个列组合为键,其余列作为值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58170435/