Reputation: 799
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
Upvotes: 2
Views: 5677
Reputation: 150735
df.loc[df['value'].between(2,7, inclusive=False), 'value'] += 1
Output:
value
0 1
1 2
2 4
3 5
4 6
5 7
6 7
7 8
8 9
9 10
Upvotes: 3
Reputation: 4761
You can do it this way:
df[(2 < df.value) & (df.value < 7)] += 1
or equivalently:
df[(df.value.gt(2)) & (df.value.lt(7))] += 1
Output in both cases:
value
0 1
1 2
2 4
3 5
4 6
5 7
6 7
7 8
8 9
9 10
Upvotes: 1