如何在 Python 中将列表作为行附加到 Pandas DataFrame?


要打开列表,我们可以使用 append() 方法。有了它,我们还可以使用 loc() 方法。首先,让我们导入所需的库 -

import pandas as pd

以下是按团队排名组织的数据 -

Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50]]

使用上述数据并添加列来创建 DataFrame -

dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

假设以下是要附加的行 -

myList = [["Sri Lanka", 6, 40]]

以列表的形式附加上述行 -

dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)

示例

以下是使用 append() 附加的代码 -

import pandas as pd

# data in the form of list of team rankings
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50]]

# Creating a DataFrame and adding columns
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

print"DataFrame...\n",dataFrame

# row to be appended
myList = [["Sri Lanka", 6, 40]]

# append the above row in the form of list
dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)

# display the update dataframe
print"\nUpdated DataFrame after appending a row...\n",dataFrame

输出

这将产生以下输出 -

DataFrame...
        Country   Rank   Points
0         India      1      100
1     Australia      2       85
2       England      3       75
3   New Zealand      4       65
4  South Africa      5       50

Updated DataFrame after appending a row...
        Country   Rank   Points
0         India      1      100
1     Australia      2       85
2       England      3       75
3   New Zealand      4       65
4  South Africa      5       50
5     Sri Lanka      6       40

让我们看另一个例子 -

示例

以下是使用 loc() 方法附加的代码 -

import pandas as pd

# data in the form of list of team rankings
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]

# Creating a DataFrame and adding columns
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

print"DataFrame...\n",dataFrame

# row to be appended
myList = ["Sri Lanka", 7, 30]

# append the above row in the form of list using loc()
dataFrame.loc[len(dataFrame)] = myList

# display the update dataframe
print"\nUpdated DataFrame after appending a row using loc...\n",dataFrame

输出

这将产生以下输出 -

DataFrame...
        Country   Rank   Points
0         India      1      100
1     Australia      2       85
2       England      3       75
3   New Zealand      4       65
4  South Africa      5       50
5    Bangladesh      6       40

Updated DataFrame after appending a row using loc...
        Country   Rank   Points
0         India      1      100
1     Australia      2       85
2       England      3       75
3   New Zealand      4       65
4  South Africa      5       50
5    Bangladesh      6       40
6     Sri Lanka      7       30

更新时间:2021-09-21

2K+ 浏览

为你的 事业取得成功

完成课程并获得认证

开始操作
广告