首页 > 解决方案 > 如何根据行的“属性”将数据帧行乘以数组,同时保留与数组属性不匹配的数据帧行?

问题描述

与“https://stackoverflow.com/questions/60566053/how-to-multiply-dataframe-rows-by-an-array-based-on-an-attribute-of-the-row”非常相似,但如果是原始的数据框的索引行与数组的属性不匹配,df 元素返回 NaN。实际上,我想要一个“左连接”变体实现

操作数 DataFrame df 示例(日期作为 A、B 和 C 列的索引):

                A     B     C
 2000-01-02     1     2     3
 2000-01-03     1     2     3
 2000-01-04     1     2     3
 2000-01-05     1     2     3

df2:

                A     B     C
 2000-01-03     1     2     3
 2000-01-04     1     2     3

试图获得元素 df*df2 乘法数据帧结果:

                A     B     C
 2000-01-02     1     2     3
 2000-01-03     1     4     9
 2000-01-04     1     4     9
 2000-01-05     1     2     3

而是得到

                A     B     C
 2000-01-02     NaN   NaN    NaN
 2000-01-03     1     4     9
 2000-01-04     1     4     9
 2000-01-05     NaN     NaN     NaN

使用基于 URL 响应的解决方案,h/t jezrael df_result = (df.mul(df2, level=0))

在 .mul() 中添加 fill_value= 作为参数无济于事

有人有什么建议吗?提前致谢

标签: pythonpandasdataframe

解决方案


您可以df使用update. 这将更新df到位

>>> df.update(df.mul(df2))
>>> df
              A    B    C
2000-01-02  1.0  2.0  3.0
2000-01-03  1.0  4.0  9.0
2000-01-04  1.0  4.0  9.0
2000-01-05  1.0  2.0  3.0

对于非就地更新,您还可以使用该fillna方法用您的第一个 df 中的值填充空值:

>>> df.mul(df2).fillna(df)
              A    B    C
2000-01-02  1.0  2.0  3.0
2000-01-03  1.0  4.0  9.0
2000-01-04  1.0  4.0  9.0
2000-01-05  1.0  2.0  3.0

推荐阅读