[英]How to convert DataFrame with Dictionary Values into other DataFrame, keys as column header
I have pandas dataframe like below:我有如下所示的熊猫数据框:
"Unnamed: 0"
0 {1:'Apple1', 2:'LemonA', 3:'StrawberryX'}
1 {1:'Apple2', 2:'LemonB', 3:'StrawberryW'}
2 {1:'Apple3', 2:'LemonC', 3:'StrawberryZ'}]
so myDf is DataFrame with 3*1 (3 rows and 1 column) What is the best way to modify it like below:所以 myDf 是具有 3*1(3 行和 1 列)的 DataFrame 什么是修改它的最佳方法,如下所示:
1 2 3
0 'Apple1' 'LemonA' 'StrawberryX'
1 'Apple2' 'LemonB' 'StrawberryW'
2 'Apple3' 'LemonC' 'StrawberryZ'
After modification my new data shape is 3*3修改后我的新数据形状是 3*3
Assuming you have a series you can do假设你有一个你可以做的系列
pd.DataFrame(list(df['"Unnamed: 0"']))
1 2 3
0 Apple1 LemonA StrawberryX
1 Apple2 LemonB StrawberryW
2 Apple3 LemonC StrawberryZ
Thanks for everyone who helped, I've just figure-out the answer to my own question感谢所有帮助我的人,我刚刚找到了我自己问题的答案
This is how I solve it,我是这样解决的
I convert all data on all rows into dictionary using pandas.DataFrame().to_dict() and save it on variable x我使用 pandas.DataFrame().to_dict() 将所有行上的所有数据转换为字典并将其保存在变量 x
Then I run the following code然后我运行以下代码
newDf = pandas.DataFrame(x) newDf = pandas.DataFrame(x)
pandas is smart enough to read dictionary keys as column. pandas 足够聪明,可以将字典键作为列读取。 :)
:)
d = {1: ['Apple1', 'Apple2', 'Apple3'], 2: ['LemonA', 'LemonB', 'LemonC'], 3: ['StrawberryX', 'StrawberryY', 'StrawberryZ']} df = pd.DataFrame(data=d) df 1 2 3 0 Apple1 LemonA StrawberryX 1 Apple2 LemonB StrawberryY 2 Apple3 LemonC StrawberryZ
d = {1: ['Apple1', 'Apple2', 'Apple3'], 2: ['LemonA', 'LemonB', 'LemonC'], 3: ['StrawberryX', 'StrawberryY', 'StrawberryZ'] } df = pd.DataFrame(data=d) df 1 2 3 0 Apple1 LemonA StrawberryX 1 Apple2 LemonB StrawberryY 2 Apple3 LemonC StrawberryZ
that would be the classic solution (you can skip putting the dictionery in the variable "d" and just write data={the data}, it just looks nicer)这将是经典的解决方案(您可以跳过将字典放在变量“d”中而只写 data={the data},它看起来更好)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.