python处理csv文件列错位,Python将csv文件列读入列表,而忽略标题

I have a file 'data.csv' that looks something like

ColA, ColB, ColC

1,2,3

4,5,6

7,8,9

I want to open and read the file columns into lists, with the 1st entry of that list omitted, e.g.

dataA = [1,4,7]

dataB = [2,5,8]

dataC = [3,6,9]

In reality there are more than 3 columns and the lists are very long, this is just an example of the format. I've tried:

csv_file = open('data.csv','rb')

csv_array = []

for row in csv.reader(csv_file, delimiter=','):

csv_array.append(row)

Where I would then allocate each index of csv_array to a list, e.g.

dataA = [int(i) for i in csv_array[0]]

But I'm getting errors:

_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

Also it feels like a very long winded way of just saving data to a few lists...

Thanks!

edit:

Here is how I solved it:

import pandas as pd

df = pd.read_csv('data.csv', names = ['ColA','ColB','ColC']

dataA = map(int,(df.ColA.tolist())[1:3])

and repeat for the rest of the columns.

解决方案

Use Pandas:

import pandas as pd

df = pd.DataFrame.from_csv(path)

rows = df.apply(lambda x: x.tolist(), axis=1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值