Python读CSV数据

Python读取CSV数据有两种:

1.按行读取csv(使用CSV库)

2.按列读取csv(使用Pandas库)

下面介绍第一种,逐行读取

1.按行读取csv(使用CSV库)

代码如下:

import csv
if __name__ =='__main__':
    filePath="test.csv"
    with open(filePath, 'r',encoding="utf-8") as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            #the first row is table header
            print(row)
            #type:list
            print(type(row))

第一个打印的row为表头的内容,之后会逐行打印所有的内容,并且row的类型为list。

2.按列读取csv(使用Pandas库)

这里以test.csv文件为例,文件一共包含两列(含表头),两列的名字分别为parameter和importance。接下来用pandas库按列读取,并分别存入到list中。

 代码如下:

import pandas as pd
if __name__ =='__main__':
    filePath="test.csv"
    df=pd.read_csv("test.csv")
    parameterList=df["parameter"].values.tolist()
    importanceList=df["importance"].values.tolist()
    print(parameterList)
    print(importanceList)

猜你喜欢

转载自blog.csdn.net/sinat_38079265/article/details/117307862