【问题标题】:I want to read a column x in a csv file and populate other columns based on the content in the column x ? How do i do that in Python?我想读取 csv 文件中的列 x 并根据列 x 中的内容填充其他列?我如何在 Python 中做到这一点?
【发布时间】:2016-11-11 10:19:35
【问题描述】:

我有一个 csv 文件。列 x 具有字符串值。根据 x 列中的值,我想在不同的 csv 中填充其他列。我该怎么做?

【问题讨论】:

  • 您尝试过什么,尝试更具体一些,举例说明您的数据和预期输出。并查看Pandas 库
  • 提及您的输入和所需的输出。
  • "in a different csv" 表示您有另一个预先存在的文件要更新,或者,您想根据第一个文件的内容创建一个新文件?

标签: python csv data-science


【解决方案1】:

如果您将行号和列号传递给函数,您也许可以这样做

def readCSVfile(line, column):
    fp = open("file")
    for i, line in enumerate(fp):
        if i == line-1:
            res = line.split(',')
    fp.close()
    return res[column]

【讨论】:

    【解决方案2】:

    我的回答解决了处理一列数据的问题 并编写一个新文件来保存处理结果。

    以下代码具有内联 cmets,我希望能够阐明其内部结构。

    # processing csv files is simple
    # but there are lots of details that can go wrong,
    # let's use a builtin module
    import csv
    
    # to abstract your (underspecified) problem, let's assume that
    # we have defined what we want to do to our data in terms
    # of a set of functions
    from my_module import f0, f1, f2, ..., fn
    
    # let's define a bunch of constants, in real life these should rather be
    # command line arguments
    input = './a/path/name.csv'a
    out = './anothe/r_path/name.csv'
    index_x = 5
    
    # slurp in the data
    with f as open(input):
        data = [row for row in csv.reader(f)]
    
    # transpose the data — list(...) is necessary for python 3
    # where zip() returns a generator
    data = list(zip(*data))
    
    # extract the data
    x = data[index_x]
    
    # the data processing is done with a double loop,
    # the outer loop on x values,
    #    the inner loop on the processing units (aka the imported functions)
    processed = [[f(item)]  for item in x for f in [f0, f1, f2, ..., fn]]
    
    # eventually, output the results of our computations to a different csv file
    # using the writerows() method that nicely iteratates on the rows of its
    # argument in our behalf
    with f as open(out, 'w'):
        csv.writer(f).writerows(processed)
    

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多