熊猫通过将两列与列表进行比较来更新列

 收藏

这似乎是一个简单的问题,但我一直在努力寻找解决方案。我有一个熊猫df,有两列(ticker,target)和一个名为stock_symbols的列表。简单来说,这就是我想要做的(请注意,这不是我的代码):

For each value in df['ticker']:
    If df['ticker'] is in [ticker_list]:
        df['target'] = 1
    Else:
        df['target'] = 0
回复
  • et_ea 回复

    Use isin for creating boolean mask which is converted to int (thanks Michael Hoff):

    df['target'] = df['ticker'].isin(ticker_list).astype(int)
    

    样品:

    ticker_list = ['s','f']
    df = pd.DataFrame({'ticker':['s','d','f']})
    print (df)
      ticker
    0      s
    1      d
    2      f
    
    df['target'] = df['ticker'].isin(ticker_list).astype(int)
    print (df)
      ticker  target
    0      s       1
    1      d       0
    2      f       1