将数据读入列表

2024-04-20 01:52:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打开一个包含100列和2行的CSV文件。我想读取文件并将第一列中的数据放入一个列表(我的x\u坐标),将第二列中的数据放入另一个列表(我的y\u坐标)

X= []
Y = []

data = open("data.csv")
headers = data.readline()
readMyDocument = data.read()


for data in readMyDocument:
    X = readMyDocument[0]
    Y = readMyDocument[1]

print(X)
print(Y)

我想得到两个列表,但是输出只是一个2的列表。 任何关于我如何改变它的建议/我的逻辑哪里是错的。你知道吗


Tags: 文件csv数据in列表forreaddata
3条回答

你可以这样做:

import csv

# No need to initilize your lists here
X = []
Y = []

with open('data.csv', 'r') as f:
    data = list(csv.reader(f))

X = data[0]
Y = data[1]

print(X)
print(Y)

看看这样行不行。你知道吗

您可以使用熊猫:

import pandas as pd
XY = pd.read_csv(path_to_file)
X = XY.iloc[:,0]
Y = XY.iloc[:,1]

或者你可以

X=[]
Y=[]
with open(path_to_file) as f:
    for line in f:
        xy = line.strip().split(',')
        X.append(xy[0])
        Y.append(xy[1])

首先:您不能关闭文件。
一个好的做法是在打开文件时使用with,这样即使代码中断也可以关闭。你知道吗

然后,如果只需要一列,可以使用列分隔符断行,只使用所需的列。你知道吗

但这只是一种学习,在实际情况中,您可能希望使用内置的csv或更好的pandas这样的库。你知道吗

X = []
Y = []

with open("data.csv") as data:
    lines = data.read().split('\n')
# headers is not being used in this spinet
headers = lines[0]
lines = lines[1:]

# changing variable name for better reading
for line in lines:
    X.append(line[0])
    Y.append(line[1])

print(X)
print(Y)

注:我忽略了一些你用过但没有在代码中声明的变量。但它们也可能是个问题。你知道吗

相关问题 更多 >