python - 从具有指定行和列名称的 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
有人可以帮我解决这个问题吗?
此致
解决方案
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 方法似乎可以节省大量时间。
推荐阅读
- postgresql - 创建用户帐户竞争条件
- php - 使用函数而不是多个 preg_matches 检查数据格式
- javascript - 使用 JS POST 下载 zip 文件
- angular - NgRx:如何模拟存储选择函数以返回不同的值
- c++ - 外部变量声明是否也声明了(对象)实体?
- python - 条形图上的seaborn重叠群图
- angular - Angular *ng用于访问数组的特定值
- python - 我想用所有列的 NA 填充由 datetime 索引的数据框中的缺失行
- java - 根据纹理视图的大小自动调整camera2的大小预览
- java - 在 wicket 应用程序中访问 Maven 依赖项的资源