将数据文件的特定列的数据查找到另一个文件的特定列,并使用python打印所有行



我有两个文本文件。在一个文件中,我有三列,数据以"|"分隔。在另一个文件中,我只有一列。示例数据集如下:

File1

CO2|44|Carbondioxide
oxygen|16|02
sulfate|96|so4

File2

co2
sulfate
NO2
so4
o2

我想在文件2中创建第二列。我想在file1的第1列和第3列中搜索file2的每个数据。如果匹配,则将文件1的相应列2值打印到文件2中的相应行。如果找不到匹配项,请保持文件2中的所有行不变。行的顺序应与原始文件2的顺序相同。所以,我的输出将如下所示:

column1           column2
co2                44
sulfate            96
NO2
SO4                 96
O2                   16

所以,到目前为止,我做了以下事情:

import pandas as pd
df1 = pd.read_csv ('file1.txt', sep='|', header=None)
df1.columns = ['pollutant1', 'mass', 'pollutant2']
df2 = pd.read_csv ('file2.txt', header=None)
df2.columns = ['pollutant']
df2["NewColumn"]= " "

我不知道如何在文件1特定的列中搜索文件2。如有任何帮助,我们将不胜感激。

我会首先遍历列1(file1(中的每个条目,并将其与文件2中的每个条目进行比较。

import pandas as pd
df1 = pd.read_csv ('file1.txt', sep='|', header=None)
df1.columns = ['pollutant1', 'mass', 'pollutant2']
df2 = pd.read_csv ('file2.txt', header=None)
df2.columns = ['pollutant']
df2["NewColumn"]= " "
# iterate through each line in column 1 in file 1
for j, line in enumerate(df1["pollutant1"]):
# now we are going to compare each entry with each line in file 2
for x, item in enumerate (df2["pollutant"]):
# we check if both entry match
# therefore we convert both entries into lower case strings
if line.lower() == item.lower():
# if they match, we will add the specific entry to df2
df2["NewColumn"][x]=df1["mass"][j]

之后,您可以遍历第3列(文件1(中的每个条目,并将其与文件2中的每个条目进行比较。

# iterate through each line in column 3 in file 1
for j, line in enumerate(df1["pollutant2"]):
# now we are going to compare each entry with each line in file 2
for x, item in enumerate (df2["pollutant"]):
# we check if both entry match
# therefore we convert both entries into lower case strings
if line.lower() == item.lower():
# if they match, we will add the specific entry to df2
df2["NewColumn"][x]=df1["mass"][j]
print(df2)

然而,";氧气";以及";o2";。这些条目无法匹配。

最新更新