Skip to main content
 首页 » 编程设计

python之将带有列表的字典添加到 Pandas DataFrame(pd.DataFrame(dict) vs df.append(dict))

2024年09月07日32luoye11

我在将包含列表的字典添加到 Pandas 数据框中时遇到问题。我的数据如下所示:

a = {'id':[0,1,2,3,4,5,6], 
 'value':[354,324,211,78,644,198,342]} 

当您将字典添加到 pandas 数据框时,它会将每个列表的元素添加到数据框中的一行,如下所示:

test1 = pd.DataFrame(a) 

但是,当我尝试附加一个字典(在本例中是同一个字典)时,每一列都包含一个列表。

test1 = test1.append(a, ignore_index = True) 

我试图找出为什么会这样。有帮助吗?

谢谢。

请您参考如下方法:

您可以再次使用 pd.DataFrame:

test1.append(pd.DataFrame(a), ignore_index=True) 

输出:

    id  value 
0    0    354 
1    1    324 
2    2    211 
3    3     78 
4    4    644 
5    5    198 
6    6    342 
7    0    354 
8    1    324 
9    2    211 
10   3     78 
11   4    644 
12   5    198 
13   6    342 

或者使用pd.concat

pd.concat([test1,pd.DataFrame(a)])