【问题标题】:Conditional Multiplication in Pandas PythonPandas Python 中的条件乘法
【发布时间】:2019-07-19 16:57:27
【问题描述】:

我想根据两列中的值进行条件乘法。

数据如下:

如果多头头寸不是nan,那么我想乘以远期执行价格,否则乘以空头头寸乘以远期执行价格。

我该怎么做?

【问题讨论】:

  • Position ShortPosition Long 中是空字符串?还是 NaN?
  • 在python中是NaN。当我复制它是空白的
  • 如果两列都是NaN,输出不变或者是NaN?
  • 一列可以是nan,另一列会有值

标签: python pandas


【解决方案1】:

如果缺失值为NaNs,则使用combine_firstfillna

s = df['Position Long'].combine_first(df['Position Short'])
#alternative
#s = df['Position Long'].fillna(df['Position Short'])

如果两列都缺失并且需要在输出中使用NaN

df['new'] = df['Forward Strike Price'].mul(s)

或者如果需要原始值:

df['new'] = df['Forward Strike Price'].mul(s, fill_value=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2022-01-15
    • 2022-12-07
    • 2016-04-27
    • 2022-08-19
    • 1970-01-01
    • 2020-10-05
    相关资源
    最近更新 更多