将字典转换为数据框(DataFrame)的方法

huangapple go评论85阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月29日 14:05:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定