gpt4 book ai didi

python - 在 Python 中仅从 CSV 文件中获取一列

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:49 25 4
gpt4 key购买 nike

我正在尝试获取三列 n 行的 csv,并将第一列的元素放入可迭代列表中。我遇到的问题是它正在获取一个如下所示的列表(在代码中为“datalist”):

[
['56529.132', '16.9199', '0.152425'], ['56529.133', '16.4637', '0.127646'],
['56529.139', '16.4859', '0.12598'], ['56529.139', '16.4011', '0.121806'],
['56529.147', '16.7835', '0.31821'], ['56529.148', '16.3248', '0.179531'],
['56529.155', '16.3012', '0.146556'], ['56529.162', '16.1506', '0.174568'],
['56529.169', '16.1904', '0.180294'], ['56529.17', '16.0262', '0.164397'],
]

并将第一列隔离为如下所示:

56529.132
56529.133
56529.139
56529.139
56529.147
56529.148
56529.155
56529.162
56529.169
56529.17

在第二个输出中,每个单独的字符本身就是一个数据元素,因此,如果我将其放入我想要的列表中,它看起来像:

['5']
['6']
['5']
['2']
['9']
['.']
['1']
['3']
['2']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['3']
['3']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['3']
['9']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['3']
['9']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['4']
['7']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['4']
['8']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['5']
['5']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['6']
['2']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['6']
['9']
['5']
['6']
['5']
['2']
['9']
['.']
['1']
['7']

我该如何解决这个问题?我需要一个列表,其中每个元素都“完整”,所以它看起来像

[['56529.132'],['56529.133'],['56529.139'],...

到目前为止我的代码:

def read_csvfile(filename):
import csv
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
datalist = list(reader)
return datalist

in_confirm = read_csvfile('bin3test.csv')

def confirm_obs(in_confirm):

for row in in_confirm:
col1 = row[0]
print(col1)


result = confirm_obs(in_confirm)

csv 中的一些数据:

56529.132   16.9199 0.152425
56529.133 16.4637 0.127646
56529.139 16.4859 0.12598
56529.139 16.4011 0.121806
56529.147 16.7835 0.31821
56529.148 16.3248 0.179531
56529.155 16.3012 0.146556
56529.162 16.1506 0.174568
56529.169 16.1904 0.180294
56529.17 16.0262 0.164397

最佳答案

我会得到这样的第一行:

first_col = [row[0] for row in in_confirm]

然后我会使用这两种方法之一获取单个字符/数字(不确定您需要哪一种):

[x for item in first_col for x in item]
# ['5', '6', '5', '2', '9', '.', '1', '3', '2', '5', ...

[[x] for item in first_col for x in item]
# [['5'], ['6'], ['5'], ['2'], ['9'], ['.'], ...

关于python - 在 Python 中仅从 CSV 文件中获取一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52955989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com