Read a CSV into list of lists in Python
Last Updated :
08 Apr, 2022
In this article, we are going to see how to read CSV files into a list of lists in Python.
- We can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.
- We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV contents to list with or without headers.
Example 1:
In this example, we are reading a CSV file and converting the string into the list.
Python3
import csv
with open ( 'sample.csv' , 'r' ) as read_obj:
csv_reader = csv.reader(read_obj)
list_of_csv = list (csv_reader)
print (list_of_csv)
|
Output:
[[‘JAN’, 34, 360, 417], [‘FEB’, 31, 342, 391], [‘MAR’, 36, 406, 419], [‘APR’, 34, 396, 461],
[‘MAY’, 36, 420, 472], [‘JUN’, 43, 472, 535], [‘JUL’, 49, 548, 622], [‘AUG’, 50, 559, 606],
[‘SEP’, 40, 463, 508], [‘OCT’, 35, 407, 461], [‘NOV’, 31, 362, 390], [‘DEC’, 33, 405, 432]]
Example 2:
In this example, we are reading a CSV file and iterating over lines in the given CSV.
Python3
import csv
with open ( 'example.csv' ) as csvfile:
readCSV = csv.reader(csvfile, delimiter = ',' )
for row in readCSV:
print (row)
print (row[ 0 ])
print (row[ 0 ], row[ 1 ], row[ 2 ],)
print ( "\n" )
|
Output:
Method 2: Using Pandas
You can use the pandas library for this which has an inbuilt method to convert values to a list. Pandas.values property is used to get a numpy.array and then use the tolist() function to convert that array to list.
Note: For more information refer Read CSV Into List Using Pandas
Python3
import pandas as pd
dict = {
'series' : [ 'Friends' , 'Money Heist' , 'Marvel' ],
'episodes' : [ 200 , 50 , 45 ],
'actors' : [ ' David Crane' , 'Alvaro' , 'Stan Lee' ]
}
df = pd.DataFrame( dict )
print (df)
|
Output:
Please Login to comment...