如何向现有的熊猫数据框添加新行?

时间:2019-07-08 09:44:44

标签: python python-3.x pandas

我有一个已定义为空的pandas数据框,然后在进行一些计算后想在其中添加一些行。

我尝试执行以下操作:

test = pd.DataFrame(columns=['Name', 'Age', 'Gender'])

if #some statement:

test.append(['James', '95', 'M'])

如果我尝试打印然后附加到测试节目中

print(test)

test.append(['a', 'a', 'a', 'a', 'a', 'a'])

print(test)

>>>

Empty DataFrame
Columns: [Name, Age, Gender]
Index: []
Empty DataFrame
Columns: [Name, Age, Gender]
Index: []

因此很明显,该行未添加到数据框中。

我希望输出为

Name | Age | Gender
James | 95 | M

6 个答案:

答案 0 :(得分:1)

您可以作为Series通过:

test.append(pd.Series(['James', 95, 'M'], index=test.columns), ignore_index=True)

[出]

    Name Age Gender
0  James  95      M

答案 1 :(得分:1)

append与字典一起使用:

test = test.append(dict(zip(test.columns,['James', '95', 'M'])), ignore_index=True)

print(test)
    Name Age Gender
0  James  95      M

答案 2 :(得分:0)

尝试将其附加为字典:

>>> test = test.append({'Name': "James", "Age": 95, "Gender": "M"}, ignore_index=True)
>>> print(test)

输出:

    Name Age Gender
0  James  95      M

答案 3 :(得分:0)

首先append方法不会就地修改DataFrame,但会返回修改后的(附加版本)。

第二,传递的新行应该是DataFramedict / Series或这些列表中的一个。

#using dict
row = {'Name': "James", "Age": 95, "Gender": "M"}
# using Series
row = pd.Series(['James', 95, 'M'], index=test.columns))

尝试print( test.append(row) )并查看结果。

您需要将test.append的返回值保存为附加版本,如果您不关心先前版本,则可以使用相同的名称保存它,

test = test.append( row )

答案 4 :(得分:0)

尝试一下

>>> test.append(dict(zip(test.columns,['James', '95', 'M'])), ignore_index=True)

    Name Age Gender
0  James  95      M

答案 5 :(得分:0)

附加功能会将列表转换为DataFrame,它会自动生成列[0],但测试的列数为['Name','Age','Gender']。并且append不会更改测试。我可能会引起混淆,运行以下代码可能会让您理解。

import pandas as pd

#Append function will convert list into DataFrame,and two dataframe object should have the same column
data = pd.DataFrame(['James', '95', 'M'])
print(data)

#right code
test = pd.DataFrame(columns=['Name', 'Age', 'Gender'])
test = test.append(pd.DataFrame([['James', '95', 'M']],columns=['Name', 'Age', 'Gender']))
print(test)