Pandas 基于列的多条件函数

Pandas Multiple Conditions Function based on Column

只是想找到最优雅的方法来对不同列中的值应用真正简单的转换,每列都有自己的条件。所以给定一个这样的数据框:

   A      B      C  D    E     F
0  1 2013-01-02  1  3   test  foo
1  1 2013-01-02  1  3  train  foo
2  1 2013-01-02  1  3   test  foo
3  1 2013-01-02  1  3  train  foo

只想拥有一个函数,仅当第二列具有特定值时才调整每列中的值。换句话说...

df['C'] = -1 if df['E'] == "test" else df['C'] next column...
df['D'] = -2 if df['E'] == "test" else df['D'] and so forth.

我在想 pandas 中的 where 函数在这里会派上用场,但不确定如何应用它。我可以执行以下操作,但似乎效率不高,我必须为每个 col 创建一个不同的函数:

def col(df):
    if df['col1'] == "value":
        return -1.00
    else:
        return relative_buckets['col1']

您可以将 .loc 与布尔系列一起使用:

>>> df
   A           B  C  D      E    F
0  1  2013-01-02  1  3   test  foo
1  1  2013-01-02  1  3  train  foo
2  1  2013-01-02  1  3   test  foo
3  1  2013-01-02  1  3  train  foo
>>> df.loc[df.E == "test", "C"] = -1
>>> df
   A           B  C  D      E    F
0  1  2013-01-02 -1  3   test  foo
1  1  2013-01-02  1  3  train  foo
2  1  2013-01-02 -1  3   test  foo
3  1  2013-01-02  1  3  train  foo

使用 .loc 比尝试直接影响列更可取,因为存在视图与复制问题(有关详细信息,请参阅 here。)

如果您想一次更改多个列,您也可以这样做:

>>> df.loc[df.E == "test", ["C","D"]] = [888, 999]
>>> df
   A           B    C    D      E    F
0  1  2013-01-02  888  999   test  foo
1  1  2013-01-02    1    3  train  foo
2  1  2013-01-02  888  999   test  foo
3  1  2013-01-02    1    3  train  foo