0

I am seeking help to assign new group values by conditions in pandas. Here is the sample dataset for your kind improvement.

import pandas

year=[1999, 2000, 2021, 2022, 2020]    
speed=[1.0, 0.5, 0.3, 2.8, 2.5 ]

d={'year':year,'speed':speed}

df=pd.DataFrame(d)
df.speed[(df.speed >= 0.0) & (df.speed < 1.0)] = 1.0
df.speed[(df.speed >= 1.0) & (df.speed < 2.0)] = 2.0
df.speed[(df.speed >= 2.0) & (df.speed < 3.0)] = 3.0
print(df)

My expectation answer is like follows:

   year  speed
0  1999    2.0
1  2000    1.0
2  2021    1.0
3  2022    3.0
4  2020    3.0

Thanks.

2 Answers 2

1

Try looking at the numpy.ceil method.

Something like this:

df['speed_ceil'] = np.ceil(df['speed'])

Would give you something like this:

    year    speed       speed_ceil
0   1999    1.033815    2.0
1   2000    0.197175    1.0
2   2001    1.837738    2.0
3   2002    1.333317    2.0
4   2003    0.349559    1.0
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the suggestion..it gives me some new inputs about other numpy application today..i will share answer of the above question soon.
0

I came to know there is solution for the above question after runs through previous post in link as follows : https://stackoverflow.com/a/71454870/8995571 by @Corralien. using numpy select.

condlist = [(df['speed'] >= 0.0) & (df['speed'] < 1.0),
            (df['speed'] >= 1.0) & (df['speed'] < 2.0),
            (df['speed'] >= 2.0) & (df['speed'] < 3.0),
            (df['speed'] >= 3.0) & (df['speed'] < 4.0)]

choicelist = [1,2,3,4]

df['speed'] = np.select(condlist, choicelist)

Result :
   year  speed
0  1999      2
1  2000      1
2  2021      1
3  2022      3
4  2020      3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.