Python 从数据帧列的列中dict
如何从dataframe的列创建字典。以下是测试代码:Python 从数据帧列的列中dict,python,pandas,dictionary,tuples,Python,Pandas,Dictionary,Tuples,如何从dataframe的列创建字典。以下是测试代码: import pandas as pd df = pd.DataFrame({ 'c0': ['A','A','B'], 'c1': ['b','c','d'], 'c2': [1, 3,4], 'c3': [5,7,8]}) 输出: c0 c1 c2 c3 0 A b 1 5 1 A c 3 7 2 B d 4 8 我想从,比如,key:(c0,c1)和val
import pandas as pd
df = pd.DataFrame({
'c0': ['A','A','B'],
'c1': ['b','c','d'],
'c2': [1, 3,4],
'c3': [5,7,8]})
输出:
c0 c1 c2 c3
0 A b 1 5
1 A c 3 7
2 B d 4 8
我想从,比如,key:(c0,c1)和value:(c2)中获得一本字典
我是这样做的
dict(zip(zip(df['c0'], df['c1']), df['c2']))
您可以与-多索引一起使用
创建元组
:
print (df.set_index(['c0','c1'])['c2'].to_dict())
{('B', 'd'): 4, ('A', 'b'): 1, ('A', 'c'): 3}
print (df.set_index(['c0','c1'])['c2'].to_dict())
{('B', 'd'): 4, ('A', 'b'): 1, ('A', 'c'): 3}