提问人:Miss_Orchid 提问时间:1/29/2019 最后编辑:VaishaliMiss_Orchid 更新时间:1/29/2019 访问量:78
匹配两个 Pandas DataFrame 值
matching two pandas dataframe values
问:
我有两个独立的熊猫数据帧:
IDr = pd.read_csv(file1,header=None,delim_whitespace=True,usecols=[0])
print IDr
0
0 467770
1 467080
2 467060
3 466950
4 A0W030
5 A0C540
6 D2F230
...
和
IDg = pd.read_csv(file2,header=None,delim_whitespace=True,usecols=[0,4])
print IDg
0 4
0 C1I230 6.5
1 466940 14.0
2 466900 0.0
25 467420 0.5
26 A0W030 -998.0
27 A0C540 0.0
28 D2F230 2.5
...
任务是匹配 IDr 中的值与 IDg 中的 id 匹配,并提取 IDg 中的第二列号(pandas 索引号)。
在某些情况下,可能没有匹配项(在这种情况下,“0”是可以的),但永远不会超过 1 个匹配项(每个文件中只有一个数字/字母组合)。
对于提供的示例,上面的匹配项将是
'-998.0' for 'A0W030',
'0.0' for A0C540, and
'2.5' for D2F230
0 for 467770, 467080, 467060, and 466950.
我已经尝试了 locate、str.contains 和 str.match 函数,但似乎没有任何效果。有什么想法吗?
答:
2赞
Vaishali
1/29/2019
#1
您可以使用合并
df1.merge(df2, how = 'left').fillna(0)
0 4
0 467770 0.0
1 467080 0.0
2 467060 0.0
3 466950 0.0
4 A0W030 -998.0
5 A0C540 0.0
6 D2F230 2.5
或者映射并将列分配给 df1
df1['new'] = df1['0'].map(df2.set_index('0')['4']).fillna(0)
0 new
0 467770 0.0
1 467080 0.0
2 467060 0.0
3 466950 0.0
4 A0W030 -998.0
5 A0C540 0.0
6 D2F230 2.5
评论