如何在Python中把一个列表作为一行追加到Pandas DataFrame中

如何在Python中把一个列表作为一行追加到Pandas DataFrame中

在这篇文章中,我们将看到如何在Python中把一个列表作为行追加到pandas数据框中。它可以通过三种方式完成。

  • 使用loc[]
  • 使用iloc[]
  • 使用append()

使用loc[]方法追加列表

Pandas DataFrame.loc属性通过标签或布尔数组访问指定DataFrame中的一组行和列。

让我们把清单上的内容分步附上:

第1步:使用列表创建一个简单的数据框架。

import pandas as pd
 
# List
Person = [ ['Satyam', 21, 'Patna' , 'India' ],
            ['Anurag', 23, 'Delhi' , 'India' ],
            ['Shubham', 27, 'Coimbatore' , 'India' ]]
 
#Create a DataFrame object
df = pd.DataFrame(Person,
                  columns = ['Name' , 'Age', 'City' , 'Country'])
 
# display
display(df)
Python

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

第2步:使用loc将新的列表追加到一个数据框中。

# New list for append into df
list = ["Saurabh", 23, "Delhi", "india"]
 
# using loc methods
df.loc[len(df)] = list
 
# display
display(df)
Python

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

使用iloc[]方法追加列表

Pandas DataFrame.iloc方法访问基于整数位置的索引,用于按位置选择。

示例:

# import module
import pandas as pd
 
# List
Person = [ ['Satyam', 21, 'Patna' , 'India' ],
            ['Anurag', 23, 'Delhi' , 'India' ],
            ['Shubham', 27, 'Coimbatore' , 'India' ],
            ["Saurabh", 23, "Delhi", "india"]]
 
#Create a DataFrame object
df = pd.DataFrame(Person,
                  columns = ['Name' , 'Age', 'City' , 'Country'])
 
# new list to append into df
list = ['Ujjawal', 22, 'Fathua', 'India']
 
# using iloc
df.iloc[2] = list
 
# display
display(df)
Python

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

注意 – 它用于基于位置的索引,所以它只对现有的索引起作用,并取代了行元素。

使用append()方法追加列表

Pandas dataframe.append()函数用于将其他数据框架的行追加到给定数据框架的末尾,返回一个新的数据框架对象。

示例:

# import module
import pandas as pd
 
# List
Person = [ ['Satyam', 21, 'Patna' , 'India' ],
            ['Anurag', 23, 'Delhi' , 'India' ],
            ['Shubham', 27, 'Coimbatore' , 'India' ]]
 
#Create a DataFrame object
df = pd.DataFrame(Person,
                  columns = ['Name' , 'Age', 'City' , 'Country'])
 
# new list to append into df
list = [["Manjeet", 25, "Delhi", "india"]]
 
# using append
df = df.append(pd.DataFrame( list,
               columns=[ 'Name', 'Age', 'City', 'Country']),
               ignore_index = True)
 
# display df
display(df)
Python

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册