提问者:小点点

将csv文件作为数据帧加载[重复]


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


共3个答案

匿名用户

Unicodesv库也可用于读取。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

匿名用户

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

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

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

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

匿名用户

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