英文:
How to transfer dictionary to dataframe
问题
我想将字典 dic_1
转换为 dataframe
(结果就像 val_1.append(val_2)
的结果一样),但是代码 pd.DataFrame(dic_1)
失败了。如何修复它?
import pandas as pd
val_1 = pd.DataFrame({'category':['a','b'],'amount':[1,3]})
val_2 = pd.DataFrame({'category':['d','e'],'amount':[4,7]})
dic_1 = {'v01':val_1,'v02':val_2}
以下代码失败
pd.DataFrame(dic_1)
如何修复它?
英文:
There is dictionary dic_1
, i want transfer it to dataframe
(the result just like the result of val_1.append(val_2)
), but code pd.DataFrame(dic_1)
failed .How to fixed it ?
import pandas as pd
val_1 = pd.DataFrame({'category':['a','b'],'amount':[1,3]})
val_2 = pd.DataFrame({'category':['d','e'],'amount':[4,7]})
dic_1 ={'v01':val_1,'v02':val_2}
below code failed
pd.DataFrame(dic_1)
答案1
得分: 1
import pandas as pd
val_1 = pd.DataFrame({'category': ['a', 'b'], 'amount': [1, 3]})
val_2 = pd.DataFrame({'category': ['d', 'e'], 'amount': [4, 7]})
dic_1 = {'v01': val_1, 'v02': val_2}
df = pd.concat(dic_1.values(), ignore_index=True)
print(df)
ignore_index=True 确保在生成的DataFrame中重置了索引。
输出结果:
category amount
0 a 1
1 b 3
2 d 4
3 e 7
如果你想要跟踪原始的DataFrames,可以移除 ignore_index=True,然后添加 keys=dic_1.keys()。
```python
df = pd.concat(dic_1.values(), keys=dic_1.keys())
输出结果:
category amount
v01 0 a 1
1 b 3
v02 0 d 4
1 e 7
英文:
import pandas as pd
val_1 = pd.DataFrame({'category':['a','b'],'amount':[1,3]})
val_2 = pd.DataFrame({'category':['d','e'],'amount':[4,7]})
dic_1 ={'v01':val_1,'v02':val_2}
df = pd.concat(dic_1.values(), ignore_index=True)
print(df)
ignore_index=True makes sure that the index is reset in the resulting DataFrame.
The output
category amount
0 a 1
1 b 3
2 d 4
3 e 7
If you want to keep track of the original DataFrames, you can remove ignore_index=True and instead add keys=dic_1.keys().
df = pd.concat(dic_1.values(), keys=dic_1.keys())
output:
category amount
v01 0 a 1
1 b 3
v02 0 d 4
1 e 7
答案2
得分: 0
pd.DataFrame 期望输入的类型如下:
{列名: 值作为列表}
但您正在将数据框传递为值。
英文:
pd.DataFrame expects input to be of following type
{columname: values as list}
But you are passing dataframe as value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论