如何在 Python 中使用 append() 将列表追加到 Pandas DataFrame?
为了使用 append() 将列表追加到 DataFrame,我们首先创建一个 DataFrame。这些数据采用团队排名的列表形式,如下所示 −
# 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'])
假设要追加的行如下 −
myList = [["Sri Lanka", 6, 40]]
使用 append() 以列表形式追加上述行 −
dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)
示例
以下为代码 −
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
广告