I have a pandas dataframe of the the form
0 x y z
1 .5 .1 4
2 .6 .2 5
我希望把前两列转换成字典列表,即 [{'x': 0.5,'y': 0.1},{'x': 0.6,'y': 0.2} ...]。
我可以写一个循环来完成这个愚蠢的方法,但有没有更好更快的方法呢?
I have a pandas dataframe of the the form
0 x y z
1 .5 .1 4
2 .6 .2 5
iteritems()
、__getitem__
等方法一样遍历行,但是返回的是Series
而不是字典。to_dict()
方法将每个Series
转换为字典。list_of_dicts = list( row.to_dict() for key, row in df.iterrows() )
使用to_dict(orient='records')
并指定orient=records
可以提高速度。
In [2]: df[['x', 'y']].to_dict(orient='records')
Out[2]:
[{'x': 0.5, 'y': 0.1}, {'x': 0.6, 'y': 0.2}]
时间
In [8]: df.shape
Out[8]: (10000, 4)
In [9]: %timeit df[['x', 'y']].to_dict(orient='records')
10 loops, best of 3: 68.4 ms per loop
In [10]: %timeit df[['x','y']].to_dict('index').values()
1 loop, best of 3: 570 ms per loop
In [11]: %timeit list(row.to_dict() for key, row in df[['x', 'y']].iterrows())
1 loop, best of 3: 575 ms per loop
to_dict()
方法。假设yourdata.csv
是以.csv格式存储的数据:df = pd.read_csv('yourdata.csv')
d = df[['x','y']].to_dict('index').values()
应该可以工作。它返回:
[{'y': 0.1, 'x': 0.5}, {'y': 0.2, 'x': 0.6}]
pd.read_csv('yourdata.csv')
导入了你的数据框。 - Fabio Lamanna