简体   繁体   English

如何从数据框字典创建 Pandas DataFrame?

[英]How to create a Pandas DataFrame from dictionary of dataframes?

I have a dictionary that is a list of dataframes that have all the same columns and data structure.我有一个字典,它是一个包含所有相同列和数据结构的数据框列表。 I am wanting to essentially 'union' all of these into a single dataframe again, where the dictionary keys are converted into another column: df_list{}我想再次将所有这些“联合”到一个数据帧中,其中字典键被转换为另一列:df_list{}

{'A' : col1 col2 col3 \
001    val1  val2  val3
002    val3  val4  val5

'B' : col1 col2 col3 \
001    val1  val2  val3
002    val3  val4  val5

...and so on ...等等

but am wanting:但我想要:

key  Col1  Col2  Col3
A    val1  val2  val3
A    val4  val5  val6
B    val1  val2  val3
B    val4  val5  val6

I tried using pd.DataFrame.from_dict() but either I am not using it right or I need something else..我尝试使用 pd.DataFrame.from_dict() 但要么我没有正确使用它要么我需要其他东西..

final_df = pd.DataFrame.from_dict(df_list)

but get: ValueError: If using all scalar values, you must pass an index但是得到:ValueError:如果使用所有标量值,则必须传递索引

when I try passing the index, I get one column back vs a dataframe.当我尝试传递索引时,我会返回一列与数据框。

This should do it:这应该这样做:

import pandas as pd

df1 = pd.DataFrame({
    "col1":['val1','val3'],
    "col2":['val2','val3'],
    "col3":['val3','val5']
})


df2 = pd.DataFrame({
    "col1":['val7','val3'],
    "col2":['val2','val3'],
    "col3":['val3','val5']
})

pd_dct = {"A": df1, "B": df2}

# adding the key in 
for key in pd_dct.keys():
    pd_dct[key]['key'] = key 

# concatenating the DataFrames
df = pd.concat(pd_dct.values())

Alternatively, we can also do this in one line with:或者,我们也可以在一行中执行此操作:

pd.concat(pd_dct, axis=0).reset_index(level=0).rename({'level_0':'key'}, axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM