根据来自另一个df的几种条件设置df的列值

时间:2019-06-18 13:02:02

标签: python pandas dataframe

我想基于另一个数据框的值将值设置为数据框

示例:

df1

A   |  B  |  C  |               
100   20.1        
100   21.3
100   22.0
100   23.6
100   24.0
100   25.8

df2

A   |  B  |  D

100   20     AC1
100   22     AC2 
100   23     AC3
100   25     AC4
100   29     AC5
200   20     AC1
200   34     AC2
200   37     AC3

我希望df1 ['C']具有类似的内容

AC1
AC1
AC2
AC3
AC3
AC4

df1['C'] = df2['D'].where((df2['A'] == df1['A']) & (df2['B'] < df1['B']))

1 个答案:

答案 0 :(得分:3)

您可以pd.mergeffill填写缺失值:

df1['C'] = pd.merge(df1, df2, how='left', on = ['A', 'B']).fillna(method='ffill')['D']

输出

+---+-----+----+-----+
|   |  A  | B  |  C  |
+---+-----+----+-----+
| 0 | 100 | 20 | AC1 |
| 1 | 100 | 21 | AC1 |
| 2 | 100 | 22 | AC2 |
| 3 | 100 | 23 | AC3 |
| 4 | 100 | 24 | AC3 |
| 5 | 100 | 25 | AC4 |
+---+-----+----+-----+

编辑:说明

首先,我们在df1df2列上合并AB

pd.merge(df1, df2, how='left', on = ['A', 'B'])
#output
+---+-----+----+-----+
|   |  A  | B  |  C  |
+---+-----+----+-----+
| 0 | 100 | 20 | AC1 |
| 1 | 100 | 21 | AC1 |
| 2 | 100 | 22 | AC2 |
| 3 | 100 | 23 | AC3 |
| 4 | 100 | 24 | AC3 |
| 5 | 100 | 25 | AC4 |
+---+-----+----+-----+

要填充缺失值,我们利用ffill方法(see docs):

  

方法:{'backfill','bfill','pad','ffill',None},默认为None   重新索引的系列填充板/填充中填充孔的方法:将最后一个有效观察向前传播到下一个有效回填/填充:使用NEXT有效观察来填充间隙

pd.merge(df1, df2, how='left', on = ['A', 'B']).fillna(method='ffill')
#output : missing values are filled as expected 
+---+-----+----+------+-----+
|   |  A  | B  |  C   |  D  |
+---+-----+----+------+-----+
| 0 | 100 | 20 | None | AC1 |
| 1 | 100 | 21 | None | AC1 |
| 2 | 100 | 22 | None | AC2 |
| 3 | 100 | 23 | None | AC3 |
| 4 | 100 | 24 | None | AC3 |
| 5 | 100 | 25 | None | AC4 |
+---+-----+----+------+-----+

df1['C']只是合并和填充数据帧的D列,这正是我们想要的

df1['C'] = pd.merge(df1, df2, how='left', on = ['A', 'B']).fillna(method='ffill')['D']