I have the following dataframe, and I would like to increment 'value' for all of the rows where value is between 2 and 7.
import pandas as pd
df = pd.DataFrame({"value": range(1,11)})
df
# Output
value
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
I have tried two ways to do this, the first attempt failed with an error. The second attempt works but it is not the nicest solution. Can anyone provide a nicer solution?
# Attempt #1
df.loc[2 < df['value'] < 7, 'value'] += 1
# Ouput
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
# Attempt #2
def increment(value):
if value > 2 and value < 7:
return value + 1
return value
df["value"] = df["value"].apply(lambda x : increment(x))
# Output
value
0 1
1 2
2 4
3 5
4 6
5 7
6 7
7 8
8 9
9 10