python读取CSV并转为数组

您所在的位置:网站首页 pandas读取一行并转换为list python读取CSV并转为数组

python读取CSV并转为数组

#python读取CSV并转为数组| 来源: 网络整理| 查看: 265

存在问题: 读取CSV,并将数据转化为数组

解决方案: 方法1: 使用pandas库

import pandas as pd data=pd.read_csv("F:\PythonFiles\PycharmFile\ex14PermutationCombination_DataIn.csv",header=None) #必须添加header=None,否则默认把第一行数据处理成列名导致缺失 list=data.values.tolist() print(list) print(list[1]) print(list[2]) print(list[1]+list[2]) print(len(list))

输出:

[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]] [2, 3] [3, 4] [2, 3, 3, 4] 6

方法2: 使用numpy库

import numpy list = numpy.loadtxt(open("F:\PythonFiles\PycharmFile\ex14PermutationCombination_DataIn.csv","rb"),delimiter=",",skiprows=0) print(list) print(list[1]) print(list[2]) print(list[1]+list[2]) print(len(list))

输出:

[[1. 2.] [2. 3.] [3. 4.] [4. 5.] [5. 6.] [6. 7.]] [2. 3.] [3. 4.] [5. 7.] 6

注: 1)pandas支持文本格式的数组转化,而numpy只支持数字格式的数组转化; 2)pandas按文本字符运算,numpy按数字运算,比较print(list[1]+list[2])即可



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3