[英]Pandas: Incrementing values in a column based on condition
I have the following dataframe, and I would like to increment 'value' for all of the rows where value is between 2 and 7.我有以下 dataframe,我想为值在 2 到 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
Try pandas.Series.between
:尝试pandas.Series.between
:
df.loc[df['value'].between(2,7, inclusive=False), 'value'] += 1
Output: Output:
value
0 1
1 2
2 4
3 5
4 6
5 7
6 7
7 8
8 9
9 10
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: Output 在这两种情况下:
value
0 1
1 2
2 4
3 5
4 6
5 7
6 7
7 8
8 9
9 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.