Create a list from rows in Pandas DataFrame | Set 2 (original) (raw)
Last Updated : 29 Jan, 2019
In an earlier post, we had discussed some approaches to extract the rows of the dataframe as a Python’s list. In this post, we will see some more methods to achieve that goal.
Note : For link to the CSV file used in the code, click here.
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.
import
pandas as pd
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
(df)
Output :
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.
Row_list
=
[]
for
i
in
range
((df.shape[
0
])):
`` Row_list.append(
list
(df.iloc[i, :]))
print
(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.
print
(
len
(Row_list))
print
(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.
import
pandas as pd
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
]})
Row_list
=
[]
for
i
in
range
((df.shape[
0
])):
`` cur_row
=
[]
`` for
j
in
range
(df.shape[
1
]):
`` cur_row.append(df.iat[i, j])
`` Row_list.append(cur_row)
print
(Row_list)
Output :
print
(
len
(Row_list))
print
(Row_list[:
3
])
Output :
Similar Reads
- Pandas Exercises and Programs Pandas is an open-source Python Library that is made mainly for working with relational or labelled data both easily and intuitively. This Python library is built on top of the NumPy library, providing various operations and data structures for manipulating numerical data and time series. Pandas is 6 min read
- Different ways to create Pandas Dataframe It is the most commonly used Pandas object. The pd.DataFrame() function is used to create a DataFrame in Pandas. There are several ways to create a Pandas Dataframe in Python. Example: Creating a DataFrame from a Dictionary [GFGTABS] Python import pandas as pd # initialize data of lists. data = { 7 min read