如何将csv文件中的某些列另存为Python中的变量? [英] How to save certain columns from csv file as variables in Python?

查看:225
本文介绍了如何将csv文件中的某些列另存为Python中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用matplotlib在Python中保存并绘制某些列的图形.列的参数将从cmdline获取,因此我将不得不使用sys.argv来获取它们.这是我目前所拥有的:

I want to save and graph certain columns in Python using matplotlib. The argument for the columns will be obtained from the cmdline, so I'll have to use sys.argv to obtain them. Here's what I have currently:

我还应该提到,列号可以根据用户选择的内容而有所不同.例如,他们可以仅执行列1, 2或仅执行列1.

I should also mention that the column numbers can vary depending on what the user chooses. For instance, they could do just columns 1, 2 or just columns 1.

with open('./P14_data.csv', 'rb') as csvfile:
    data = csv.reader(csvfile, delimiter=';')
    cols = [index for index in sys.argv[1:]]

    #I want to extract the columns corresponding to cols

    for col in cols:

    x[col] = [rows for rows in data]
    print x

但这将返回一个空列表[].

But this returns an empty list [].

对于输出,我想将每一列绘制为一维数组.因此,例如,使用以下格式的csv文件:

As for the output, I'd like to graph each column as a one-dimensional array. So for instance, with a csv file of the form:

1 5 
1 3
0 2
0 3
1 1
1 3

如果用户输入'1',我希望我的代码仅将第一列变量保存在数组中:

If a user inputs '1', I want my code to save only column one variables in an array:

data = [[1, 1, 0, 0,..]]

plt.plot(data)

我知道熊猫是一个有效的选择,但我想先这样学习.谢谢!

I know pandas is a valid option, but I like to learn it this way first. Thanks!

推荐答案

好吧,您可以尝试这样的事情:

Well you could try something like that:

#!/usr/bin/env python3

import csv

with open('./P14_data.csv', newline='') as csvfile:
    data = csv.reader(csvfile, delimiter=';')
    x = [rows for rows in data]
    transposed = list(zip(*x))
    print(transposed)

或更简单:

#!/usr/bin/env python3

import csv

with open('./P14_data.csv', newline='') as csvfile:
    data = csv.reader(csvfile, delimiter=';')
    transposed = list(zip(*data))
    print(transposed)

要点:

  • zip()
  • Unpacking function argument list
  • The return value of csv.reader() is an iterable of iterables

这篇关于如何将csv文件中的某些列另存为Python中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆