如何通过匹配其他列中的值来填充列子集中的缺失值?

How to fill missing values in a subset of columns by matching values in other columns?

我有一个数据框 df1 = DataFrame({'col1':['a','b','a','c'], 'col2':[1,2,1,1],'col3':['e1','e2',np.nan,'e5'],'col4':[4,5,6,6]})。 我想通过查找 col1col2 中的 values/matching 值来填充 col3 中的缺失值,以获得以下输出:

col1 col2 col3 col4
a     1    e1   4 
b     2    e2   5 
a     1    e1   6 
c     1    e5   6 

其中 col1col2 列中的值 a 和 1 return e1 for col3

我们能做的就是尝试使用 groupbyffill

df1.fillna(df1.groupby(['col1','col2']).ffill(), inplace=True)
  col1  col2 col3  col4
0    a     1   e1     4
1    b     2   e2     5
2    a     1   e1     6
3    c     1   e5     6

与 YOBEN_S' 答案(我更喜欢)非常相似的方法,但使用 fillna:

df.col3 = df.groupby(['col1', 'col2']).fillna(method='ffill').col3