从Pandas数据框架中的行创建一个列表

从Pandas数据框架中的行创建一个列表

Python的list很容易操作,而且list有很多内置的函数可以对list进行大量的操作。Pandas数据框架的列由系列组成,但与列不同,Pandas数据框架的行没有任何类似的关联。在这篇文章中,我们将讨论几种方法,我们可以一次提取数据框架的整个行。

解决方案#1:为了迭代Pandas数据框架的行,我们可以使用DataFrame.iterrows()函数,然后我们可以将每一行的数据追加到列表的最后。

# importing pandas as pd
import pandas as pd
  
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                    'Cost':[10000, 5000, 15000, 2000]})
  
# Print the dataframe
print(df)

输出 :

从Pandas数据框架中的行创建一个列表

现在我们将使用DataFrame.iterrows()函数来遍历给定Dataframe的每一行,并从每一行的数据中构建一个列表。

# Create an empty list
Row_list =[]
  
# Iterate over each row
for index, rows in df.iterrows():
    # Create list for the current row
    my_list =[rows.Date, rows.Event, rows.Cost]
      
    # append the list to the final list
    Row_list.append(my_list)
  
# Print the list
print(Row_list)

输出 :

从Pandas数据框架中的行创建一个列表

正如我们在输出中看到的,我们已经成功地将给定数据框架的每一行提取成一个列表。就像其他 Python 的列表一样,我们可以在提取的列表上执行任何列表操作。

# Find the length of the newly 
# created list
print(len(Row_list))
  
# Print the first 3 elements
print(Row_list[:3])

输出 :

从Pandas数据框架中的行创建一个列表

从Pandas数据框架中的行创建一个列表

解决方案#2:为了迭代Pandas数据框架的行,我们可以使用DataFrame.itertuples()函数,然后我们可以将每一行的数据追加到列表的最后。

# importing pandas as pd
import pandas as pd
  
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                    'Cost':[10000, 5000, 15000, 2000]})
  
# Print the dataframe
print(df)

输出 :

从Pandas数据框架中的行创建一个列表

现在我们将使用DataFrame.itertuples()函数来遍历给定Dataframe的每一行,并从每一行的数据中构建一个列表。

# Create an empty list
Row_list =[]
  
# Iterate over each row
for rows in df.itertuples():
    # Create list for the current row
    my_list =[rows.Date, rows.Event, rows.Cost]
      
    # append the list to the final list
    Row_list.append(my_list)
  
# Print the list
print(Row_list)

输出 :

从Pandas数据框架中的行创建一个列表

正如我们在输出中看到的,我们已经成功地将给定的数据框架的每一行提取成一个列表。就像其他 Python 的列表一样,我们可以在提取的列表上执行任何列表操作。

# Find the length of the newly 
# created list
print(len(Row_list))
  
# Print the first 3 elements
print(Row_list[:3])

输出 :

从Pandas数据框架中的行创建一个列表

从Pandas数据框架中的行创建一个列表

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程