我在 pandas 中有以下 2 个数据框
df1
date tank quantity
2018-04-01 1 234
2018-04-02 1 343
2018-04-03 1 334
2018-04-04 1 143
2018-04-05 1 237
2018-04-06 1 234
2018-04-07 1 last observation
2018-04-01 2 234
2018-04-02 2 343
2018-04-03 2 334
2018-04-04 2 143
2018-04-05 2 237
2018-04-06 2 234
2018-04-07 2 last observation
df2
date tank quantity
2018-04-01 1 221
2018-04-02 1 200
2018-04-03 1 100
2018-04-04 1 123
2018-04-05 1 234.56
2018-04-06 1 324.67
2018-04-07 1 324.67
2018-04-01 2 221
2018-04-02 2 221.23
2018-04-03 2 222.21
2018-04-04 2 453
2018-04-05 2 443
2018-04-06 2 234
2018-04-07 2 456
我想要的数据框看起来像
df1
date tank quantity
2018-04-01 1 234
2018-04-02 1 343
2018-04-03 1 334
2018-04-04 1 143
2018-04-05 1 237
2018-04-06 1 234
2018-04-07 1 324.67
2018-04-01 2 234
2018-04-02 2 343
2018-04-03 2 334
2018-04-04 2 143
2018-04-05 2 237
2018-04-06 2 234
2018-04-07 2 456
我只想替换 df2 中的值,其中数量列值是 df1 中的 last observation
。
我怎样才能在 pandas 中做到这一点?
最佳答案
使用 np.where
:
df1['quantity'] = np.where(df1['quantity'].eq('last observation'), df2['quantity'],
df1['quantity']).astype(float)
或mask
:
df1['quantity'] = df1['quantity'].mask(df1['quantity'].eq('last observation'),
df2['quantity']).astype(float)
或where
:
df1['quantity'] = df1['quantity'].where(df1['quantity'].ne('last observation'),
df2['quantity']).astype(float)
关于pandas - 如何从 Pandas 中的两个数据帧做条件映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54287438/