Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - How can I add a label in a new column in pandas based on two consecutive values of another column?

I've got a dataframe, df, with a single column, extension.
The values in extension column are cyclically increasing and decreasing like below:

extension
0.000
0.050
0.100
0.150
0.130
0.080
0.020
0.050
0.075

I'm trying to label each increasing and decreasing cycle like below:

extension lablel
0.000      1
0.050      1
0.100      1
0.150      1
0.130      1
0.080      1
0.020      1
0.050      2
0.075      2

I'm a bit stuck, and would appreciate some guidance here.

question from:https://stackoverflow.com/questions/65911134/how-can-i-add-a-label-in-a-new-column-in-pandas-based-on-two-consecutive-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
df['lablel']=df.extension.diff()#Find the difference between consecutive ros in the column extension
df['lablel']=(df.lablel.ge(0)&df.lablel.shift(1).le(0)|df.lablel.ge(0)&df.lablel.shift(-1).le(0)).cumsum()+1#Find zero crossing from the consecutive differences, cummulatively sum and add 1 to the outcome



 extension  lablel
0      0.000       1
1      0.050       1
2      0.100       1
3      0.150       2
4      0.130       2
5      0.080       2
6      0.020       2
7      0.050       3
8      0.075       3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...