This is a noob question, but without using Pandas (pd.read) how can I import a CSV file and load it to a DataFrame object so I can call it (e.g. print (loaded_file) ) and print the contents of the file in Python (2.7)?
Asked
Active
Viewed 5,685 times
3 Answers
2
unicodecsv library can also be used to read .csv files.
import unicodecsv
import pandas as pd
def read_csv(data):
""" Returns a list of dicts from .csv file passed in as data"""
with open(data, "rb") as f:
reader = list(unicodecsv.DictReader(f))
return reader
file = read_csv('filename.csv') # call the function and pass in your 'filename'
pd.DataFrame(file) # call pd.DataFrame() function with file as an argument
# to convert it to DataFrame object
Mr.Pacman
- 320
- 2
- 7
1
import pandas as pd
data = pd.read_csv('file_name')
Martin Thoma
- 108,021
- 142
- 552
- 849
Hackaholic
- 17,534
- 3
- 51
- 68
-
3The question *just* mentioned without pandas... – tyteen4a03 May 03 '17 at 10:29
1
Just read each line and split, also notice that you will need to know hoy to parse the types, for example:
def getCSV(filePath, sep=";"):
with open(filePath, "r") as f:
return [l.split(sep) for l in f]
then just load it into a pandas dataframe:
import pandas as pd
csvdata = getCSV("/da/real/path/file.csv")
pd.DataFrame(csvdata)
Netwave
- 36,219
- 6
- 36
- 71
-
-
`getCSV` returns a list of lists (python lists) containing the data (string type) of the csv file. @Alvis – Netwave May 03 '17 at 10:38
-