简体   繁体   中英

How to apply a function to some values in a dataframe column

I have this single line of code that checks if a dataframe column is between the range of a value.

data.loc[data.day<6, 'month'] -= 1

The above code works fine for the entire dataframe, but I only want to apply it to the key column with value equal to salary

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

Expected output:

          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

I have tried using this filter query data[[data.key == 'salary'].day<13, 'month'] -= 1 which resulted to the below error

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'

tried this as well

new = data.loc[data.key == 'salary'] , new.loc[new.day<6, 'month'] -=1 This worked but I want to do it in a single line rather than assigning a variable new to it.

You can combine multiple conditions into one Boolean index by using logical operators and surrounding each condition with parentheses:

data.loc[(data.day < 6) & (data.key == "salary"), "month"] -= 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM