根据if is not value regex填充新列

2024-05-18 23:43:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在数据帧中构建一个新列,其中只填充与if is not匹配的行。我目前正在填充所有行,这就是问题所在。在下面的结果中,我不应该看到.*_TO_CLOSE行,它应该是None,用“Open”填充

def strategy_type():
    for row in TRADER_READER['Action']:
        open = re.search('.*_TO_OPEN$', str(row))
        if open is not None:
            TRADER_READER['Strategy'] = 'Open'
    print(TRADER_READER)


strategy_type()

返回:

2020-03-27 16:15:00  Receive Deliver  EXPIRE_TO_CLOSE  ...         PUT     Open
2020-03-31 17:00:00  Receive Deliver      BUY_TO_OPEN  ...         NaN     Open
2020-03-31 17:00:00  Receive Deliver  EXPIRE_TO_CLOSE  ...         PUT     Open
2020-04-01 11:00:05            Trade    SELL_TO_CLOSE  ...         NaN     Open
2020-04-01 11:00:05            Trade    SELL_TO_CLOSE  ...         PUT     Open

Tags: tononecloseifputistypenot
3条回答

如果要寻找矢量化解决方案,请查看以下内容。考虑列名称的更改可能与您的

不同。
           Date  time        deliver            status              
0   2020-03-27  16:15:00    Receive-Deliver     EXPIRE_TO_CLOSE     
1   2020-03-31  17:00:00    Receive-Deliver     BUY_TO_OPEN 
2   2020-03-31  17:00:00    Receive-Deliver     EXPIRE_TO_CLOSE 
3   2020-04-01  11:00:05    Trade               SELL_TO_CLOSE   
4   2020-04-01  11:00:05    Trade               SELL_TO_CLOSE   

涂口罩

m=df.status.str.contains(r'TO_OPEN')
m

填充栏

df.loc[m,'availability']='open'
df

结果

enter image description here

代码所做的是,每当正则表达式不返回none时,就再次创建列策略。我想试试这样的东西

def check_open(x):
  open = re.search('.*_TO_OPEN$', str(x))
  return 'Open' if open is not None else None

TRADER_READER['strategy'] = TRADER_READER['action'].apply(check_open)

我认为使用熊猫的str.contains功能会更简单、更快: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html

TRADER_READER['Action'].astype(str) 
StratDictionary = {True: 'Open', False: 'Close' } 
TRADER_READER['Strategy']=TRADER_READER['Action'].str.contains('.*_TO_OPEN$', regex=True).replace(StratDictionary)

相关问题 更多 >

    热门问题