How to read csv file in python?
I am trying to solve a classification problem, where the labels of my image data are written in csv file. What is the best way to read a CSV file in Python?
I'm using Python3.6 and Ubuntu 18.04.
I am trying to solve a classification problem, where the labels of my image data are written in csv file. What is the best way to read a CSV file in Python?
I'm using Python3.6 and Ubuntu 18.04.
There is a very known python package called pandas, which is a CSV module and has a lot of functionalities like reading and writing CSV files. Here are some simple examples of how to read the CSV file.
import pandas as pd
# short example fo python read csv file
data = pd.read_csv('my_file.csv')
print(data)
#0 John Doe 120 jefferson st. Riverside NJ 08075
#1 Jack McGinnis 220 hobo Av. Phila PA 9119
#2 John "Da Man" Repici 120 Jefferson St. Riverside NJ 8075
#3 Stephen Tyler 7452 Terrace "At the Plaza" road SomeTown SD 91234
If your CSV file contains headers with the names, you can get them separately, read only the values of those columns, or combine each row with its field name.
print(data.keys)
Index(['John', 'Doe', '120 jefferson st.', 'Riverside', ' NJ', ' 08075'], dtype='object')
print(data.values)
array([['Jack', 'McGinnis', '220 hobo Av.', 'Phila', ' PA', 9119],
['John "Da Man"', 'Repici', '120 Jefferson St.', 'Riverside',' NJ', 8075],
['Stephen', 'Tyler', '7452 Terrace "At the Plaza" road','SomeTown', 'SD', 91234],
['Joan "the bone", Anne', 'Jet', '9th, at Terrace plc','Desert City', 'CO', 123]], dtype=object)
data.items() function will return a generator for pair-by-pair combination and you can use any loop iterator on it to get the field and values from the data frame.
Hi you can read it using pandas.read_csv() or using csv library's csv.reader()