如何使用 Python 中的 loc 将列表追加到 Pandas DataFrame?
Dataframe.loc 用于通过标签或布尔数组访问一组行和列。我们将使用 loc 将列表追加到 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],['Bangladesh', 6, 40]] # Creating a DataFrame and adding columns dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])
以下是待追加的行 −
myList = ["Sri Lanka", 7, 30]
使用 loc() 以列表形式追加上面的行 −
dataFrame.loc[len(dataFrame)] = myList
示例
以下是代码 −
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
广告