I'm a python beginner.Thank you for your cooperation.
The following works fine, but
df['ud_flag'] = df.apply (lambdax:1 if x.p == 1 else (-1 if x.p = -1 else 0), Axis == 1)
As a flag of ud, only a value of 1 or -1 is desired.
In other words, I would like to keep the part where ud is 0 as 1 or -1, so if I correct it as below, I will get an error.
df['ud_flag'] = df.apply (lambdax:1 if x.p==1 else (-1 if x.p==-1 else x.p.shift(1),axis=1))
Error Contents
AttributeError: ("'int' object has no attribute 'shift', 'occurred at index 0')
Data
udud_flag
0
0
1
0
0
-1
0
1
0
0
shift() is a function that shifts rows and columns relative to an array.
Therefore, I don't think it can be used for int type.
It's not shift()
, but how about wearing a mask to fill in the front hole?
import pandas as pd
df = pd.DataFrame({'ud':'0'0
0
1
0
0
-1
0
1
0
0''.split('\n')})
df['ud_flag'] = df.mask(df['ud'] == '0').fillna(method='ffill')\
.fillna('0')
© 2024 OneMinuteCode. All rights reserved.