如何将列表作为一行附加到 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 #以团队排名列表形式的数据 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 #要追加的行 myList = [["Sri Lanka", 6, 40]] #以列表的形式追加上一行 dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True) #显示更新数据框 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 #以团队排名列表形式的数据 Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]] #创建DataFrame并添加列 dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points']) print"DataFrame...\n",dataFrame #要追加的行 myList = ["Sri Lanka", 7, 30] #以列表的形式追加上一行 using loc() dataFrame.loc[len(dataFrame)] = myList #显示更新数据框 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