【问题标题】:Read a column then write in another column from a CSV file with Python使用 Python 从 CSV 文件中读取一列,然后写入另一列
【发布时间】:2017-01-09 15:03:26
【问题描述】:

我有一个包含 10 行 5 列的 CSV 文件。

对于每一行,除了第一行, 我需要阅读第 2 列并识别单元格的开头或结尾。 根据脚本在每列 2 上读取的内容,它会在同一行的第 6 列中写入一个字母。

如果您能帮助我,请提前非常感谢!

这是我的代码:

with open('test.csv', 'rb') as u:
        read = csv.reader(u)
        for line in read:
            for row[2] in rows:
                if line.endswith('this_is_a_text'):
                    writer.writerow(row[6]+["WIN"])

【问题讨论】:

  • 啊哈..这有什么问题吗?
  • 我认为行是在其他地方定义的?
  • 它给出:" for row[2] in rows: NameError: name 'rows' is not defined "
  • 发布您的输入文件和预期输出。你的问题不清楚。
  • 输入:c773522e clinical.xml fdcfdf81d3974096e6e3d458461e3a60 55273活BCR XML 5522fcfc htseq.counts.gz 1adf2b92e54f678e99e15b74ea5ed653 24 5966提交TXT预期输出:c773522e clinical.xml fdcfdf81d3974096e6e3d458461e3a60 55273活BCR XML clin_ovarian_cancer 5522fcfc htseq.counts .gz 1adf2b92e54f678e99e15b74ea5ed653 24‌​5966 提交 TXT d‌​rug_paclitaxel

标签: python csv pandas data-science


【解决方案1】:

如果那是您的实际代码,则您在当前范围内没有可用的变量“rows”。你有“线”。也许你的意思是

for row in reader

??我正在阅读的文档说一行是一行,你的行/行中应该有列。

【讨论】:

  • 如果我替换: for line in read: for row[2] in rows: by for row in reader 我有这个: Traceback(最近一次调用最后):文件“test_ouverture_gzip.py”,行56、在 if line.endswith('this_is_a_text'): NameError: name 'line' is not defined
  • 那是因为 'row' 是行。将 line.endswith ('this_is_a_text') 替换为 row.endswith ('this_is_a_text')。当您看到 NameError: name 'variablename' is not defined 时,这意味着您必须查看代码并询问自己在引发错误的范围内是否存在具有给定名称的变量。我给你一个提示:没有。使用该名称定义一个变量,您的代码将继续工作(如果您在所述变量上调用正确的方法等,希望是正确的)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 2023-02-21
相关资源
最近更新 更多