python - 如何根据行的“属性”将数据帧行乘以数组,同时保留与数组属性不匹配的数据帧行?
问题描述
与“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= 作为参数无济于事
有人有什么建议吗?提前致谢
解决方案
您可以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
推荐阅读
- angular - 如果 Angular 5 中数组长度为 0,则显示消息
- python - Python web 使用过滤器抓取表格
- machine-learning - 什么是聚类多维数据的好方法?
- ruby-on-rails - 在大型 Ruby on Rails 应用程序中强制执行逻辑模型边界
- python - 如何将 np.power 应用于数据帧
- python - 如何使用 request.GET.get 方法从 django rest 框架中的 url 获取参数?
- python - 如何用excel中的另一个替换特定列中的特定单词
- kubernetes - 用于分蘖部署的 Helm init 卡在 ContainerCREATING 状态
- html - 如何在单击角度 7 中的按钮时获取下拉列表的选定值和选定文本
- c# - 当它应该是内部密封类时,无法在模拟方法中返回接口