熊猫数据帧到dict

问题描述 投票:1回答:3

我有一个数据帧:

pd.DataFrame([[1,2,3],[111,222,333]], columns=['A', 'B', 'C'])

     A    B    C
0    1    2    3
1  111  222  333
2   11   22   33

我需要将A和C中的每一行转换为dict。 我应该能够得到这个:

{'1':'3',
 '111':'333',
 '11':'33'}

到目前为止,我还没有找到如何选择应包含哪些列以及如何不包含标题

python pandas dictionary
3个回答
2
投票

来自zip

dict(zip(df.A,df.C))
Out[1073]: {1: 3, 11: 33, 111: 333}

更新

from collections import defaultdict
d = defaultdict(dict)
for _,x in df.iterrows():
    d[x['A']][x['B']] = x['C']


d
Out[74]: defaultdict(dict, {1: {2: 3}, 11: {22: 33}, 111: {222: 333}})

2
投票

这是一种方式:

d = df.set_index('A')['C'].to_dict()

1
投票

多谢你们!以下是有人想知道优化的差异:

%%timeit
d1 = df.set_index('A')['C'].to_dict()

[Out]: 2.46 ms ± 11.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
d2 = dict(zip(df['A'],df['C']))

[Out]: 1.23 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
© www.soinside.com 2019 - 2024. All rights reserved.