Создайте список из строк в фрейме данных Pandas

Опубликовано: 28 Марта, 2022

Со списком Python легко работать, а также в списке есть множество встроенных функций для выполнения множества операций со списками. Столбцы фрейма данных Pandas состоят из серий, но, в отличие от столбцов, строки фрейма данных Pandas не имеют подобной связи. В этом посте мы собираемся обсудить несколько способов извлечения всей строки фрейма данных за раз.

Solution #1: In order to iterate over the rows of the Pandas dataframe we can use DataFrame.iterrows() function and then we can append the data of each row to the end of the list.

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

Выход :

Now we will use the DataFrame.iterrows() function to iterate over each of the row of the given Dataframe and construct a list out of the data of each row.

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

Выход :

As we can see in the output, we have successfully extracted each row of the given dataframe into a list. Just like any other Python’s list we can perform any list operation on the extracted list.

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

Выход :

Solution #2: In order to iterate over the rows of the Pandas dataframe we can use DataFrame.itertuples() function and then we can append the data of each row to the end of the list.

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

Выход :

Now we will use the DataFrame.itertuples() function to iterate over each of the row of the given Dataframe and construct a list out of the data of each row.

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

Выход :

As we can see in the output, we have successfully extracted each row of the given dataframe into a list. Just like any other Python’s list we can perform any list operation on the extracted list.

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

Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.