【问题标题】:extract specific data from a csv file with specified row and column names从具有指定行和列名称的 csv 文件中提取特定数据
【发布时间】:2020-07-10 10:11:43
【问题描述】:

python 的 CSV 模块对我来说非常新,希望在特定任务上获得一些帮助。 我希望根据行名和列名从 csv-file-1 中提取数据(数值)。其次,我想将此数据放入另一个 csv 文件中,在一个新列中,与 csv-file-1 中的原始名称数据对应的同一行。

以下是我的两个数据框的示例(csv 格式,sep = ","): csv-file-1:

seq_label,id3,id4
id1,0.3,0.2
id2,0.4,0.7

csv-file-2:

seq_label,x1,...
id1,id3,...
id2,id4,...

例如,我想从 csv-file-1 中选择值,这些值对应于 csv-file-2 中“seq_label”和“x1”变量的行名的交集。 然后,我想创建一个新的 csv-file (csv-file-3),它是 csv-file-1 和从 csv-file-1 中提取的数据的融合,这样:

csv-file-3(“x3”是新变量或提取值的新列):

seq_label,x1,...,x3
id1,id3,...,0.3
id2,id4,...,0.7

有人可以帮我解决这个问题吗?

最好的问候

【问题讨论】:

  • 嘿!您似乎在要求某人为您编写一些代码。 Stack Overflow 是一个问答网站,而不是代码编写服务。您应该添加到目前为止您尝试过的内容以及您遇到的问题。请参阅here 了解如何编写有效的问题。

标签: python csv data-extraction


【解决方案1】:

这只是一个例子,用 cmets 来解释这些步骤。希望对你有帮助。

import csv

with open("path to file", "r") as f:    # to open the file with read mode
     r = csv.reader(f)                  # create a csv reader
     content = list(r)                  # get the content of the file in a list
     column = ["x3", 0.3, 0.7, ...]     # prepare the last column
     content.append(column)             # add it to content list
     with open("path to file 2", "w") as f2 :   ## Open file 2 in order to write into it
         w = csv.writer(r, newline='')
         w.writerows(content)                   ## write the new content

【讨论】:

    【解决方案2】:

    csv 库将为您返回每行的列表。 你想做的是

    read the first csv
    and convert it into something you can use (depends on whether you want row or column based access
    do the same for csv2
    for each line of csv1 search for a match in csv2
    and add it to your internal data
    write this data to your output file
    

    您可能还想看看 https://pandas.pydata.org/ 因为使用 pandas 而不是普通的 csv 方法,您似乎可以节省大量时间。

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多