带有 numpy 数组的 Python Pandas 字典

Luk*_*yer 2 numpy python-3.x pandas

我有一个如下所示的熊猫 df:

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
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个字典,以索引为键,作为值,一个包含该行所有值的 numpy 数组。所以:

0 => [0.880952, 0.623637]
...
Run Code Online (Sandbox Code Playgroud)

我知道有一个来自 Pandas 的函数 to_dict('index') ,但这会产生一个字典而不是 numpy 数组作为值。

有任何想法吗?谢谢!

jez*_*ael 7

如果需要list

您需要先转置,然后使用参数orient='list'

d = df.T.to_dict('list')
Run Code Online (Sandbox Code Playgroud)

或使用zip

d = dict(zip(df.index, df.values.tolist()))
Run Code Online (Sandbox Code Playgroud)

如果需要numpy array

d = dict(zip(df.index, df.values))
Run Code Online (Sandbox Code Playgroud)