簡體   English   中英

如何將 function 應用於 dataframe 列中的某些值

[英]How to apply a function to some values in a dataframe column

我有這行代碼來檢查 dataframe 列是否在值的范圍之間。

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

上面的代碼適用於整個 dataframe,但我只想將其應用於值等於salarykey

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

預期 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

我嘗試使用此過濾器查詢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這行得通,但我想在一行中完成,而不是分配一個變量新手。

您可以通過使用邏輯運算符並將每個條件用括號括起來,將多個條件組合成一個 Boolean 索引:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM