[英]Construct Pandas DataFrame from dictionary in form {index: list of row values}
I've managed to do this using: 我设法使用以下方法:
dft = pd.DataFrame.from_dict({
0: [50, 45, 00, 00],
1: [53, 48, 00, 00],
2: [56, 53, 00, 00],
3: [54, 49, 00, 00],
4: [53, 48, 00, 00],
5: [50, 45, 00, 00]
}, orient='index'
)
Done like this, the constructor looks just like the DataFrame making it easy to read/edit: 完成后,构造函数看起来就像DataFrame一样,易于阅读/编辑:
>>> dft
0 1 2 3
0 50 45 0 0
1 53 48 0 0
2 56 53 0 0
3 54 49 0 0
4 53 48 0 0
5 50 45 0 0
But the DataFrame.from_dict constructor doesn't have a columns parameter, so giving the columns sensible names takes an additional step: 但DataFrame.from_dict构造函数没有columns参数,因此为列提供合理的名称需要额外的步骤:
dft.columns = ['A', 'B', 'C', 'D']
This seems clunky for such a handy (eg for unit tests) way to initialise DataFrames. 对于这种方便(例如用于单元测试)初始化DataFrames的方式来说,这似乎很笨拙。
So I wonder: is there a better way? 所以我想知道:有更好的方法吗?
Alternatively you could use DataFrame.from_items()
to construct the DataFrame from your dictionary; 或者,您可以使用
DataFrame.from_items()
从您的字典构造DataFrame; this allows you to pass in the column names at the same time. 这允许您同时传入列名。
For example, if d
is your dictionary: 例如,如果
d
是你的字典:
d = {0: [50, 45, 0, 0],
1: [53, 48, 0, 0],
2: [56, 53, 0, 0],
3: [54, 49, 0, 0],
4: [53, 48, 0, 0],
5: [50, 45, 0, 0]}
The data is d.items()
and the orient is again 'index'
. 数据是
d.items()
,而orient也是'index'
。 The dictionary keys become the index values: 字典键成为索引值:
>>> pd.DataFrame.from_items(d.items(),
orient='index',
columns=['A','B','C','D'])
A B C D
0 50 45 0 0
1 53 48 0 0
2 56 53 0 0
3 54 49 0 0
4 53 48 0 0
5 50 45 0 0
In Python 2 you can use d.iteritems()
to yield the contents of the dictionary to avoid creating another list in memory. 在Python 2中,您可以使用
d.iteritems()
来生成字典的内容,以避免在内存中创建另一个列表。
One way to do that is the following: 一种方法是:
df = pd.DataFrame.from_dict({
0: {"A":50, "B":40},
1: {"A":51, "B":30}}, orient='index')
However, for quick test initialization I would probably prefer your way + then setting the columns. 但是,为了快速测试初始化,我可能更喜欢你的方式+然后设置列。
You could try: 你可以尝试:
x=pd.DataFrame({0:[50,45],1:[53,48],2:[56,53]}, index=["A","B"]).transpose()
But it's still odd as you are specifying the standard index as keys for your dictionary. 但是,当您将标准索引指定为字典的键时,它仍然很奇怪。
Why not directly 为何不直接
x = pd.DataFrame({"A":[50,53,56],"B":...})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.