📌  相关文章
📜  从 Pandas 数据框中的行创建列表

📅  最后修改于: 2022-05-13 01:54:33.151000             🧑  作者: Mango

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

Python 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)

输出 :

现在我们将使用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)

输出 :

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

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

输出 :

解决方案#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)

输出 :

现在我们将使用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)

输出 :

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

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

输出 :