【问题标题】:How to apply a function to some values in a dataframe column如何将函数应用于数据框列中的某些值
【发布时间】:2021-04-02 14:38:55
【问题描述】:

我有这行代码来检查数据框列是否在值的范围之间。

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

上面的代码适用于整个数据框,但我只想将其应用于值等于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

预期输出:

          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&lt;6, 'month'] -=1 这可行,但我想在一行中完成,而不是为其分配一个新变量。

【问题讨论】:

  • 试试data.loc[(data.day &lt; 6) &amp; (data.key == 'salary'), 'month']

标签: python pandas


【解决方案1】:

您可以通过使用逻辑运算符并将每个条件用括号括起来,将多个条件组合成一个布尔索引:

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

【讨论】:

    猜你喜欢
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多