Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 匹配两个dataframe中的两列,如果它们匹配,则获取相应的列值_Python_Python 3.x - Fatal编程技术网

Python 匹配两个dataframe中的两列,如果它们匹配,则获取相应的列值

Python 匹配两个dataframe中的两列,如果它们匹配,则获取相应的列值,python,python-3.x,Python,Python 3.x,我有两个数据Df1和Df2。我的Df1['Col2]中有几行是空的。我想用相应的Df2值填充这一空行 Df1 Col1 Col2 1 AA 2 2 2 3 AC 3 AC Df2 Cluster label 1 AA 2 AB 3 AC 4 AD Desired Output Col1 Col2 1 AA 2 AB 2 AB 2 AB 3

我有两个数据
Df1
Df2
。我的
Df1['Col2]
中有几行是空的。我想用相应的
Df2
值填充这一空行

Df1
Col1 Col2
1    AA
2   
2   
2   
3    AC
3    AC

Df2
Cluster label
1        AA
2        AB
3        AC
4        AD

Desired Output

Col1    Col2
1       AA
2       AB
2       AB
2       AB
3       AC
3       AC
我正在尝试以下代码,但没有得到结果:

Df1['Col2'] =np.where((Df2['Cluster']==Df1['Col1']),Df2['label'],'No label found')

我不能使用
merge
函数,因为我还有一些其他约束。

您可以将应用与col2上的条件结合起来

df1{"col2"] = df1.apply(lambda x: df2[df2['Cluster'] == x ['col1']]['label'].tolist()[0] if x['col2'] is None else x['col2'], axis = 1)

你可以使用字典,不是很优雅,但可能很有用

cluster_dict = df2.set_index('Cluster')['label'].to_dict()
df1.set_index('Col1')['Col2'].fillna(cluster_dict).reset_index()

   col1 col2
0     1   AA
1     2   AB
2     2   AB
3     2   AB
4     3   AC
5     3   AC