【问题标题】:How do I read CSV files and put it in list with Python?如何读取 CSV 文件并将其放入 Python 列表中?
【发布时间】:2020-12-07 09:51:02
【问题描述】:

对不起,我是菜鸟。 我有一个这样的 csv 文件

customerID , gender , ...
5575-GNVDE , Female , ...
9763-GRSKD , Male   , ...

我想把“customerID”列放在列表中

例如:

print(customerID)

喜欢

[5575-GNVDE, 9763-GRSKD , ...]

我已经写好了代码

csvFile = open("WA_Fn-UseC_-Telco-Customer-Churn.csv", "r")
reader = csv.reader(csvFile)
# create list
customerID = []
for item in reader:
    # ignore first line
    if reader.line_num == 1:
        continue
    customerID += item[0]

print(customerID)
csvFile.close()

它是这样显示的

['5', '5', '7', '5', '-', 'G', 'N', 'V', 'D', 'E','9', '7', '6', '3', '-', 'G', 'R', 'S', 'K', 'D',...]

我已经读过了:

请帮助我。 谢谢。

【问题讨论】:

  • 使用 pandas 库。方法是pandas.read_csv

标签: python csv


【解决方案1】:

你正在使用这个:

    customerID += item[0]

但这并不像你认为的那样。 customerID 是一个列表,并且您在其上使用了 add 运算符,因此 Python 尝试将 item[0] 也解释为一个列表,这是一个 str,但可以被认为是一个字符列表 - 所以这正是添加了什么。

改为使用:

    customerID.append(item[0])

或者,如果您愿意:

    customerID += [item[0]]

【讨论】:

    猜你喜欢
    • 2014-08-27
    • 2020-11-23
    • 2017-03-13
    • 2015-07-11
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多