【问题标题】:Replace all duplicate rows with Nan or blank用 Nan 或空白替换所有重复的行
【发布时间】:2021-05-31 18:23:06
【问题描述】:

我有一个具有不同“价格”的数据框 (df),我想比较这些价格并做出决定。

df['Decision'] = np.where((df['price1'] > df['price2']) ,'sell',np.where((df['price1'] < df['price2']),'buy',np.nan))

我的输出是:

price1 price2 Decision
50 50 NaN
100 200 buy
70 140 buy
150 200 buy
150 50 sell
60 20 sell
30 70 buy
60 100 buy

但我只想拥有“买入”或“卖出”的“第一个信号”并删除复制直到下一个信号,如:

price1 price2 Decision
50 50 NaN
100 200 buy
70 140
150 200
150 50 sell
60 20
30 70 buy
60 100

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用Series.where:

    m = df['Decision'].ne(df['Decision'].shift()) 
    df['Decision'] = df['Decision'].where(m, '')
    print (df)
       price1  price2 Decision
    0      50      50      NaN
    1     100     200      buy
    2      70     140         
    3     150     200         
    4     150      50     sell
    5      60      20         
    6      30      70      buy
    7      60     100         
    

    或者:

    m = df['Decision'].ne(df['Decision'].shift()) 
    df['Decision'] = np.where(m, df['Decision'], '')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2015-08-04
      • 2012-11-06
      相关资源
      最近更新 更多