将数组的Python字典转换为数据框
问题描述:
我有一个数组字典,如下所示:
I have a dictionary of arrays like the following:
d = {'a': [1,2], 'b': [3,4], 'c': [5,6]}
我想创建一个这样的熊猫数据框:
I want to create a pandas dataframe like this:
0 1 2
0 a 1 2
1 b 3 4
2 c 5 6
我编写了以下代码:
pd.DataFrame(list(d.items()))
返回:
0 1
0 a [1,2]
1 b [3,4]
2 c [5,6]
你知道我如何实现我的目标吗?!
Do you know how can I achieve my goal?!
先谢谢您.
答
Pandas允许您以一种简单的方式做到这一点:
Pandas allows you to do this in a straightforward fashion:
pd.DataFrame.from_dict(d,orient = 'index')
>> 0 1
a 1 2
b 3 4
c 5 6
pd.DataFrame.from_dict(d,orient ='index').reset_index()
为您提供所需的内容.
pd.DataFrame.from_dict(d,orient = 'index').reset_index()
gives you what you are looking for.