Создайте список из строк в Pandas DataFrame | Комплект 2
В более ранней публикации мы обсудили некоторые подходы к извлечению строк фрейма данных в виде списка Python. В этом посте мы увидим еще несколько методов для достижения этой цели.
Примечание. Для ссылки на CSV-файл, используемый в коде, щелкните здесь.
Solution #1: In order to access the data of each row of the Pandas dataframe, we can use DataFrame.iloc attribute and then we can append the data of each row to the end of the list.
# importing pandas as pdimport pandas as pd # Create the dataframedf = 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 dataframeprint(df) |
Выход :
Now we will use the DataFrame.iloc attribute to access the values of each row in the dataframe and then we will construct a list out of it.
# Create an empty listRow_list =[] # Iterate over each rowfor i in range((df.shape[0])): # Using iloc to access the values of # the current row denoted by "i" Row_list.append(list(df.iloc[i, :])) # Print the listprint(Row_list) |
Output :
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 listprint(len(Row_list)) # Print the first 3 elementsprint(Row_list[:3]) |
Output :

Solution #2: In order to access the data of each row of the Pandas dataframe we can use DataFrame.iat attribute and then we can append the data of each row to the end of the list.
# importing pandas as pdimport pandas as pd # Create the dataframedf = 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]}) # Create an empty listRow_list =[] # Iterate over each rowfor i in range((df.shape[0])): # Create a list to store the data # of the current row cur_row =[] # iterate over all the columns for j in range(df.shape[1]): # append the data of each # column to the list cur_row.append(df.iat[i, j]) # append the current row to the list Row_list.append(cur_row) # Print the listprint(Row_list) |
Output :
# Find the length of the newly # created listprint(len(Row_list)) # Print the first 3 elementsprint(Row_list[:3]) |
Выход : 

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