将csv文件加载为数据帧

时间:2017-05-03 10:27:30

标签: python

这是一个noob问题,但是如果不使用Pandas(pd.read),我如何导入CSV文件并将其加载到DataFrame对象,以便我可以调用它(例如print(loaded_file))并打印内容Python(2.7)中的文件?

3 个答案:

答案 0 :(得分:2)

unicodecsv库也可用于读取.csv文件。

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

答案 1 :(得分:1)

只需阅读每一行并拆分,还要注意你需要知道hoy来解析类型,例如:

def getCSV(filePath, sep=";"):
    with open(filePath, "r") as f:
        return [l.split(sep) for l in f]

然后只需将其加载到pandas数据帧中:

import pandas as pd
csvdata = getCSV("/da/real/path/file.csv")
pd.DataFrame(csvdata)

答案 2 :(得分:0)

import pandas as pd
data = pd.read_csv('file_name')