所以我有一个DataFrame
,我给列a-I加了标签,我想做一个Dictionary of Dictionaries
,其中外键是列“a”,内键是列“d”,值是“e”。我知道如何通过遍历每一行来实现这一点,但我觉得有一种更有效的方法可以使用DataFrame.to_dict()
来实现这一点,但我不知道DataFrame.group_by
可能会有什么帮助,但这似乎是用来分组列或索引ID的。在
如何使用pandas
(或numpy
)高效地创建Dictionary of Dictionaries
,而不必遍历每一行?我已经展示了我当前方法的一个例子,以及下面期望的输出。在
#!/usr/bin/python
import numpy as np
import pandas as pd
tmp_array = np.array([['AAA', 86880690, 86914111, '22RV1', 2, 2, 'H', '-'], ['ABA', 86880690, 86914111, 'A549', 2, 2, 'L', '-'], ['AAC', 86880690, 86914111, 'BFTC-905', 3, 3, 'H', '-'], ['AAB', 86880690, 86914111, 'BT-20', 2, 2, 'H', '-'], ['AAA', 86880690, 86914111, 'C32', 2, 2, 'H', '-']])
DF = pd.DataFrame(tmp_array,columns=["a,b,c,d,e,g,h,i".split(",")])
#print(DF)
a b c d e g h i
0 AAA 86880690 86914111 22RV1 2 2 H -
1 ABA 86880690 86914111 A549 2 2 L -
2 AAC 86880690 86914111 BFTC-905 3 3 H -
3 AAB 86880690 86914111 BT-20 2 2 H -
4 AAA 86880690 86914111 C32 2 2 H -
from collections import defaultdict
from itertools import izip
D_a_d_e = defaultdict(dict)
for a,d,e in izip(DF["a"],DF["d"],DF["e"]):
D_a_d_e[a][d] = e
#print(D_a_d_e)
#ignore the defaultdict part
defaultdict(<type 'dict'>, {'ABA': {'A549': '2'}, 'AAA': {'22RV1': '2', 'C32': '2'}, 'AAC': {'BFTC-905': '3'}, 'AAB': {'BT-20': '2'}})
我看到了这个https://stackoverflow.com/questions/28820254/how-to-create-a-pandas-dataframe-using-a-dictionary-in-a-single-column,但它有点不同,它也没有答案。在
有一个^{} 方法:
记住这一点,您可以进行groupby:
^{pr2}$也就是说,你可以使用直接向上的多重索引,而不是字典词典:
它的工作原理大致相同:
但这将是一个更节省空间/你仍然在熊猫。
大致如下:
相关问题 更多 >
编程相关推荐