【发布时间】:2021-04-02 14:38:55
【问题描述】:
我有这行代码来检查数据框列是否在值的范围之间。
data.loc[data.day<6, 'month'] -= 1
上面的代码适用于整个数据框,但我只想将其应用于值等于salary 的key 列
data
amount day month key
0 111627.94 1 6 salary
474 131794.61 31 10 salary
590 131794.61 29 11 salary
1003 102497.94 11 7 other_income
1245 98597.94 1 8 other_income
2446 5000.00 2 7 other_income
2447 10000.00 2 7 other_income
预期输出:
amount day month key
0 111627.94 1 5 salary
474 131794.61 31 10 salary
590 131794.61 29 11 salary
1003 102497.94 11 7 other_income
1245 98597.94 1 8 other_income
2446 5000.00 2 7 other_income
2447 10000.00 2 7 other_income
我已尝试使用此过滤器查询
data[[data.key == 'salary'].day<13, 'month'] -= 1 导致以下错误
AttributeError Traceback (most recent call last)
<ipython-input-773-81b5a31a7b9f> in <module>
----> 1 test_df[[test_df.key == 'salary'].day<13, 'month'] -= 1
AttributeError: 'list' object has no attribute 'day'
也试过了
new = data.loc[data.key == 'salary'], new.loc[new.day<6, 'month'] -=1 这可行,但我想在一行中完成,而不是为其分配一个新变量。
【问题讨论】:
-
试试
data.loc[(data.day < 6) & (data.key == 'salary'), 'month']