【问题标题】:Extract one column of csv into a comma separated list python将一列csv提取成逗号分隔的列表python
【发布时间】:2015-01-09 07:34:13
【问题描述】:

我有一个 CSV 文件,如下所示:

with open ("ann.csv", "rb") as annotate:
    for col in annotate:
        ann = col.lower().split(",")
        print ann[0]

我的 CSV 文件如下所示:

H1,H2,H3
da,ta,one
dat,a,two

我的输出如下所示:

da
dat

但我想要一个逗号分隔的输出,例如 (da,dat)。我怎样才能做到这一点?如果您在投票之前给我一个想法,我将非常感激。

【问题讨论】:

  • 你的意思是你想让它们在一行中并用逗号分隔?
  • @m170897017 没错!
  • 您的脚本实际上会输出H1<newline>da<newline>dat - 您是否要跳过标题?
  • @TimPietzcker 我愿意。你的回答对我很有用。谢谢你。会接受它几分钟。

标签: python csv split comma strip


【解决方案1】:

首先,在 Python 中,您有 csv module - 使用它。

其次,您正在遍历行,因此使用 col 作为变量名有点令人困惑。

第三,只需收集列表中的项目并使用.join()打印:

import csv
with open ("ann.csv", "rb") as csvfile:
    reader = csv.reader(csvfile)
    reader.next() # Skip the header row
    collected = []
    for row in reader:
        collected.append(row[0])
    print ",".join(collected)

【讨论】:

  • @Li-aungYip:谢谢你加逗号,我忘了。
  • 没问题。并且 +1 用于使用 csv 模块而不是 split(','),这不允许在数据中使用逗号文字。
【解决方案2】:

试试这样:

with open ("ann.csv", "rb") as annotate:
    output = []
    next(annotate)    # next will advanced the file pointer to next line
    for col in annotate:
        output.append(col.lower().split(",")[0])
    print ",".join(output)

【讨论】:

    【解决方案3】:

    然后试试这个:

    result = ''
    with open ("ann.csv", "rb") as annotate:
        for col in annotate:
            ann = col.lower().split(",")
            # add first element of every line to one string and separate them by comma
            result = result + ann[0] + ','
    
    print result        
    

    【讨论】:

      【解决方案4】:

      试试这个

      >>> with open ("ann.csv", "rb") as annotate:
      ...     for col in annotate:
      ...         ann = col.lower().split(",")
      ...         print ann[0]+',',
      ... 
      

      【讨论】:

        【解决方案5】:

        与其当场打印,不如建立一个字符串,最后打印出来。

        s = ''
        with open ("ann.csv", "rb") as annotate:
            for col in annotate:
                ann = col.lower().split(",")
                s += ann[0] + ','
        s = s[:-1] # Remove last comma
        print(s)
        

        我还建议更改变量名col,它是循环遍历行,而不是列。

        【讨论】:

        • 错字。最后一个 += 应该是一个 +。我已经改了。
        【解决方案6】:

        使用numpy.loadtxt 可能会更容易一些:

        In [23]: import numpy as np
            ...: fn = 'a.csv'
            ...: m = np.loadtxt(fn, dtype=str, delimiter=',')
            ...: print m
        [['H1' 'H2' 'H3']
         ['da' 'ta' 'one']
         ['dat' 'a' 'two']]
        
        In [24]: m[:,0][1:]
        Out[24]: 
        array(['da', 'dat'], 
              dtype='|S3')
        
        In [25]: print ','.join(m[:,0][1:])
        da,dat
        

        m[:,0] 获取矩阵m 的第一列,[1:] 跳过第一个元素'H1'

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-04-28
          • 2011-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-20
          • 2023-04-06
          相关资源
          最近更新 更多