Pandas:根据条件增加列中的值



我有以下数据框,我想为所有值在2到7之间的行增加'value'。

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

我已经尝试了两种方法来做到这一点,第一次尝试失败了一个错误。第二次尝试奏效了,但并不是最好的解决方案。有人能提供更好的解决方案吗?

# 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

尝试pandas.Series.between:

df.loc[df['value'].between(2,7, inclusive=False), 'value'] += 1

输出:

value
0      1
1      2
2      4
3      5
4      6
5      7
6      7
7      8
8      9
9     10

你可以这样做:

df[(2 < df.value) & (df.value < 7)] += 1

或等价:

df[(df.value.gt(2)) & (df.value.lt(7))] += 1

两种情况的输出:

value
0      1
1      2
2      4
3      5
4      6
5      7
6      7
7      8
8      9
9     10

最新更新