How to use shift()

Asked 2 years ago, Updated 2 years ago, 50 views

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

python pandas

2022-09-30 20:13

2 Answers

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.


2022-09-30 20:13

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')


2022-09-30 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.