带有numpy数组的Python Pandas字典 [英] Python Pandas Dictionary with numpy arrays
本文介绍了带有numpy数组的Python Pandas字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似以下的df熊猫:
I have a pandas df like the following:
import pandas as pd
import numpy as np
data = np.random.rand(10,2)
data
array([[0.88095214, 0.62363749],
[0.99251732, 0.97059244],
[0.00781931, 0.91413354],
[0.06914494, 0.15208756],
[0.16956942, 0.5940167 ],
[0.82641049, 0.91961484],
[0.75171128, 0.85216832],
[0.69719183, 0.49129458],
[0.93801912, 0.94206815],
[0.0730068 , 0.06453355]])
df = pd.DataFrame(data=data, index=range(10), columns = ["col1","col2"])
df
col1 col2
0 0.880952 0.623637
1 0.992517 0.970592
2 0.007819 0.914134
3 0.069145 0.152088
4 0.169569 0.594017
5 0.826410 0.919615
6 0.751711 0.852168
7 0.697192 0.491295
8 0.938019 0.942068
9 0.073007 0.064534
现在,我想创建一个字典,将索引作为键,并将该行中的所有值作为一个numpy数组作为值. 所以:
Now I want to create an dictionary with the index as key and as a value a numpy array with all values in that line. So:
0 => [0.880952, 0.623637]
...
我知道熊猫有一个函数to_dict('index'),但这会产生一个字典,而不是numpy数组作为值.
I know there is a function to_dict('index') from pandas, but this yields a dictionary instead of numpy array as values.
有什么想法吗?谢谢!
推荐答案
如果需要list
s:
首先需要转置,然后使用参数orient='list'
:
You need transpose first and then use parameter orient='list'
:
d = df.T.to_dict('list')
或使用zip
:
d = dict(zip(df.index, df.values.tolist()))
如果需要numpy array
s:
If need numpy array
s:
d = dict(zip(df.index, df.values))
这篇关于带有numpy数组的Python Pandas字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文