【问题标题】:Separating positive and negative values of pandas DataFrame分离pandas DataFrame的正负值
【发布时间】:2016-02-05 02:41:30
【问题描述】:

我需要分别对列中的所有正负值求和,即

pos_values = [x for x in df.prediction_at_ohlcv_end_date if x > 0] 
neg_values = [x for x in df.prediction_at_ohlcv_end_date if x < 0] 

这是一个数据样本

market_trading_pair next_future_timestep_return ohlcv_start_date    prediction_at_ohlcv_end_date
0   Poloniex_ETH_BTC    0.003013    1450753200  -0.157053
1   Poloniex_ETH_BTC    -0.006521   1450756800  -0.920074
2   Poloniex_ETH_BTC    0.003171    1450760400  0.999806
3   Poloniex_ETH_BTC    -0.003083   1450764000  0.627140
4   Poloniex_ETH_BTC    -0.001382   1450767600  0.999857

在 pandas 中有什么好的方法可以做到这一点?

编辑:

感谢一些有用的堆叠器,我已经能够做到这一点,但我意识到我无法进行进一步的计算。 `

if prediction_at_ohlcv_end_date > 0 : 
return = prediction_at_ohlcv_end_date * next_future_timestep_return. 

对于框架中的每个元素,有什么想法吗?`

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以为您的特定列使用pandas.Seriessum 方法:

    neg = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date < 0].sum()
    pos = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date >= 0].sum()
    
    In [51]: pos
    Out[51]: 2.6268029999999998
    
    In [52]: neg
    Out[52]: -1.077127
    

    为了你的价值观:

    pos_values = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date >= 0]
    neg_values = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date < 0]
    

    编辑

    对于您的编辑,您可以这样做:

    mask = df.prediction_at_ohlcv_end_date >= 0
    res = df.prediction_at_ohlcv_end_date[mask] * df.next_future_timestep_return[mask]
    
    In [10]: res
    Out[10]: 
    2    0.003170
    3   -0.001933
    4   -0.001382
    dtype: float64
    

    【讨论】:

    • 您也可以使用query 稍微缩短命令:pos = df.query('prediction_at_ohlcv_end_date &gt; 0').sum()
    • 嘿,非常感谢。真的很大的帮助。我好像忘记了我需要做的另一项操作,你有没有机会看看我的编辑?
    猜你喜欢
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2022-10-22
    • 2016-02-17
    相关资源
    最近更新 更多