首页 > 解决方案 > 从具有指定行和列名称的 csv 文件中提取特定数据

问题描述

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 文件 2:

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

例如,我想从 csv-file-1 中选择值,这些值对应于 csv-file-2 中“seq_label”和“x1”变量的行名的交集。然后,我想创建一个新的 csv 文件(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

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

此致

标签: pythoncsvdata-extraction

解决方案


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 方法似乎可以节省大量时间。


推荐阅读