Python 如何将两列值转换为键值对字典?
如何将下面数据框中的列中的值转换为键-值对字典,如Python 如何将两列值转换为键值对字典?,python,pandas,Python,Pandas,如何将下面数据框中的列中的值转换为键-值对字典,如{“a”:29,“b”:1042,“c”:2928,“d”:4492} event_type count 0 a 29 1 b 1042 2 c 2928 3 d 4492 一种方法是使用zip: dict(zip(*df.values.T)) # {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492} 如果
{“a”:29,“b”:1042,“c”:2928,“d”:4492}
event_type count
0 a 29
1 b 1042
2 c 2928
3 d 4492
一种方法是使用
zip
:
dict(zip(*df.values.T))
# {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}
如果dataframe包含更多列:
dict(zip(df['event_type'], df['count']))
# {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}
一种方法是使用
zip
:
dict(zip(*df.values.T))
# {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}
如果dataframe包含更多列:
dict(zip(df['event_type'], df['count']))
# {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}
创建
系列
并转换为目录
:
d = df.set_index('event_type')['count'].to_dict()
print (d)
{'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}
创建
系列
并转换为目录
:
d = df.set_index('event_type')['count'].to_dict()
print (d)
{'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}
df.to_dict()
这不会产生预期的结果@joan你需要一个系列,正如耶兹雷尔的回答df.to_dict()
这不会产生预期的结果@joan你需要一个系列,正如在jezrael的回答中一样,这项与dataframe有关的工作是否包含两个以上的列?是否更新了适用于此类情况的替代方案@LoremIpsumDolor?这项与dataframe有关的工作是否包含两个以上的列?是否更新了适用于此类情况的替代方案@LoremIpsumDolor