Python 如何将csv文件中的值添加到列表中?

Python 如何将csv文件中的值添加到列表中?,python,csv,matplotlib,plot,Python,Csv,Matplotlib,Plot,如何将x的每个值和y的值放在一个列表中? 我基本上是在尝试创建一个绘图。使用pandas x,y 6.1101,17.592 5.5277,9.1302 8.5186,13.662 7.0032,11.854 5.8598,6.8233 8.3829,11.886 7.4764,4.3483 8.5781,12 6.4862,6.5987 5.0546,3.8166 5.7107,3.2522 14.164,15.505 使用pandas,如下示例 作为pd进口熊猫 df=pd.read\u

如何将x的每个值和y的值放在一个列表中?
我基本上是在尝试创建一个绘图。

使用
pandas

x,y
6.1101,17.592
5.5277,9.1302
8.5186,13.662
7.0032,11.854
5.8598,6.8233
8.3829,11.886
7.4764,4.3483
8.5781,12
6.4862,6.5987
5.0546,3.8166
5.7107,3.2522
14.164,15.505

使用
pandas
,如下示例


作为pd进口熊猫
df=pd.read\u csv('data.csv'))
x=df.x.tolist()
y=df.y.tolist()
x
y
变量将分别包含
CSV
列表中
x
y
列中的值。

您可以:

import pandas as pd
df=pd.read_csv('myfile.csv', sep=',',header=None)
给出:

import csv
from collections import defaultdict

columns = defaultdict(list)
with open("my.csv") as fin:
    dr = csv.DictReader(fin)
    for row in dr:
        for key, val in row.items():
            columns[key].append(float(val))

print(columns["x"])
print(columns["y"])

显然,这是假设内容将是需要转换为
float
(正如问题所述,您正在尝试创建绘图)的数字数据。如果存在非数值,这将引发一个
ValueError
,因此如果出现这种情况,则需要对此进行测试或处理异常。

简单的方法是使用csv模块功能。 首先创建一个csv阅读器函数:

[6.1101, 5.5277, 8.5186, 7.0032, 5.8598, 8.3829, 7.4764, 8.5781, 6.4862, 5.0546, 5.7107]
[17.592, 9.1302, 13.662, 11.854, 6.8233, 11.886, 4.3483, 12.0, 6.5987, 3.8166, 3.2522]
上面的函数返回一个可以迭代的生成器,如果您的csv文件非常大,因此不需要立即将其放入内存中,这将非常有用。 然后使用该函数读取数据并迭代这些值

import csv

def csv_dict_reader(file, has_header=False, skip_comment_char=None, **kwargs):
    """
    Reads CSV file into memory


    :param file: (str) path to csv file to read
    :param has_header: (bool) skip first line
    :param skip_comment_char: (str) optional character which, if found on first row, will skip row
    :param delimiter: (char) CSV delimiter char
    :param fieldnames: (list) CSV field names for dictionnary creation
    :param kwargs:
    :return: csv object that can be iterated
    """
    with open(file) as fp:
        csv_data = csv.DictReader(fp, **kwargs)
        # Skip header
        if has_header:
            next(csv_data)

        fieldnames = kwargs.get('fieldnames')
        for row in csv_data:
            # Skip commented out entries
            if fieldnames is not None:
                if skip_comment_char is not None:
                    if not row[fieldnames[0]].startswith(skip_comment_char):
                        yield row
                else:
                    yield row
            else:
                # list(row)[0] is key from row, works with Python 3.7+
                if skip_comment_char is not None:
                    if not row[list(row)[0]].startswith(skip_comment_char):
                        yield row
                else:
                yield row
顺便说一句,也许使用两个单独的列表不是最优化的方式。
您可以删除这两个列表,只需直接使用
行['x']

您可以使用
pandas
执行此操作:

fieldnames = ('x', 'y')
data = csv_dict_reader('/path/to/my/file')
x_list = []
y_list = []
for row in data:
    x_list.append(row['x'])
    y_list.append(row['y'])
输出:

import pandas as pd

df = pd.read_csv('cord.csv', sep=',')

x = df['x'].tolist()
y = df['y'].tolist()
作为pd进口熊猫

df=pd.read\u csv('data.csv',header=None)

打印(类型(测向列))

打印(类型(测向索引))

一旦知道了数据集的默认类型,就可以使用 df.columns.tolist()

df.index.tolist()

打印(类型(data.columns.tolist())
打印(键入(data.index.tolist())

您尝试了什么?如果你不知道怎么做,我想我会等到你有了更多的经验后再尝试ML…技术上说,OP要求list@SuperStewOP:
所以我可以把它用于机器学习
仅仅因为OP想把它用于“机器学习”,并不意味着你应该假设他想用熊猫。OP要求把他的数据放在一个列表中,而你却给了他一个数据框。@JacekRojek是的,但那是他的problem@SuperStew只是因为它为您处理标题行。啊,这是handylist没有
add
方法-您的意思是
append
?@alaniwi谢谢,当您在晚上11点发表评论时就会出现这种情况;)
[6.1101, 5.5277, 8.5186, 7.0032, 5.8598, 8.3829, 7.4764, 8.5781, 6.4862, 5.0546, 5.7107, 14.164]
[17.592, 9.1302, 13.662, 11.854, 6.8233, 11.886, 4.3483, 12.0, 6.5987, 3.8166, 3.2522, 15.505]