gpt4 book ai didi

python - 使用 csv 模块从 csv 文件中读取特定列?

转载 作者:IT老高 更新时间:2023-10-28 12:26:21 25 4
gpt4 key购买 nike

我正在尝试解析 csv 文件并仅从特定列中提取数据。

示例 csv:

ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |

我正在尝试仅捕获特定列,例如 IDNameZipPhone

我看过的代码让我相信我可以通过相应的数字来调用特定的列,所以即: Name 将对应于 2 并迭代使用 row[2] 的每一行都会产生第 2 列中的所有项目。只有它不会。

这是我到目前为止所做的:

import sys, argparse, csv
from settings import *

# command arguments
parser = argparse.ArgumentParser(description='csv to postgres',\
fromfile_prefix_chars="@" )
parser.add_argument('file', help='csv file to import', action='store')
args = parser.parse_args()
csv_file = args.file

# open csv file
with open(csv_file, 'rb') as csvfile:

# get number of columns
for line in csvfile.readlines():
array = line.split(',')
first_item = array[0]

num_columns = len(array)
csvfile.seek(0)

reader = csv.reader(csvfile, delimiter=' ')
included_cols = [1, 2, 6, 7]

for row in reader:
content = list(row[i] for i in included_cols)
print content

我希望这只会打印出我想要的每一行的特定列,除非它没有,我只得到最后一列。

最佳答案

从该代码中获取最后一列的唯一方法是,如果您不将打印语句 in 包含在您的 for 循环中。

这很可能是您的代码的结尾:

for row in reader:
content = list(row[i] for i in included_cols)
print content

你希望它是这样的:

for row in reader:
content = list(row[i] for i in included_cols)
print content

既然我们已经解决了您的错误,我想借此时间向您介绍pandas。模块。

Pandas 在处理 csv 文件方面非常出色,您只需以下代码即可读取 csv 并将整列保存到变量中:

import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']

因此,如果您想将列 Names 中的所有信息保存到一个变量中,您需要做的就是:

names = df.Names

这是一个很棒的模块,我建议您研究一下。如果由于某种原因您的打印语句在 for 循环中并且它仍然只打印出最后一列,这不应该发生,但如果我的假设是错误的,请告诉我。您发布的代码有很多缩进错误,因此很难知道应该在哪里。希望这对您有所帮助!

关于python - 使用 csv 模块从 csv 文件中读取特定列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16503560/

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