如何在 Python 中使用 append() 将列表附加到 Pandas DataFrame?
要使用将列表附加到DataFrameappend(),让我们首先创建一个DataFrame。对于我们的示例,数据采用团队排名列表的形式-
#以团队排名列表形式的数据 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]]
使用append()-以列表的形式附加上一行-
dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)
示例
以下是代码-
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']) print"DataFrame...\n",dataFrame #rowtobeappended myList = [["Sri Lanka", 6, 40]] #appendtheaboverowintheformoflist dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True) #displaytheupdatedataframe 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