[英]Fill new Pandas column based on if is not value regex
I am trying to build a new column in a data frame where only the rows that match an if is not
are filled.我正在尝试在数据框中构建一个新列,其中只有与
if is not
填充。 I am currently filling all the rows, which is the issue.我目前正在填写所有行,这就是问题所在。 In the results below, I shouldn't see the
.*_TO_CLOSE
rows, which should be None
, filling with 'Open'.在下面的结果中,我不应该看到
.*_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()
Returns:回报:
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
If looking for a vectorised solution.Look at the following.如果要寻找矢量化解决方案。请查看以下内容。 Consider change in column names maybe different with yours
考虑更改列名可能与您的不同
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
apply mask敷面膜
m=df.status.str.contains(r'TO_OPEN')
m
Fill column填充列
df.loc[m,'availability']='open'
df
Outcome结果
What you're code is doing is every time the regex not returns none you're creating the column strategy again.您正在做的代码是每次正则表达式不返回任何内容时,您都会再次创建列策略。 I would try something like
我会尝试类似的东西
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)
I think it could be easier and quicker to use str.contains function of pandas: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html I think it could be easier and quicker to use str.contains function of pandas: 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.