在 Pandas/python 中使用 .loc 嵌套 if 语句

sin*_*047 5 python if-statement dataframe python-3.x pandas

我在像下面的代码这样的条件语句中使用 if 。如果 address 是 NJ,则 name 列的值更改为“N/A”。

df1.loc[df1.Address.isin(['NJ']), 'name'] = 'N/A'
Run Code Online (Sandbox Code Playgroud)

如果我有像下面这样的“嵌套 if 语句”,我该怎么做?

# this not code just representing the logic
if address isin ('NJ', 'NY'):
    if name1 isin ('john', 'bob'):
        name1 = 'N/A' 
    if name2 isin ('mayer', 'dylan'):
        name2 = 'N/A'
Run Code Online (Sandbox Code Playgroud)

我可以使用实现上述逻辑df.loc吗?或者有其他方法可以做到吗?

jpp*_*jpp 4

正如@MartijnPeiters 所示,对于少数条件来说,单独的分配是一个好主意。

对于大量条件,请考虑使用numpy.select来分隔您的条件和选择。这应该使您的代码更具可读性并且更易于维护。

例如:

import pandas as pd, numpy as np

df = pd.DataFrame({'address': ['NY', 'CA', 'NJ', 'NY', 'WS'],
                   'name1': ['john', 'mayer', 'dylan', 'bob', 'mary'],
                   'name2': ['mayer', 'dylan', 'mayer', 'bob', 'bob']})

address_mask = df['address'].isin(('NJ', 'NY'))

conditions = [address_mask & df['name1'].isin(('john', 'bob')),
              address_mask & df['name2'].isin(('mayer', 'dylan'))]

choices = ['Option 1', 'Option 2']

df['result'] = np.select(conditions, choices)

print(df)

  address  name1  name2    result
0      NY   john  mayer  Option 1
1      CA  mayer  dylan         0
2      NJ  dylan  mayer  Option 2
3      NY    bob    bob  Option 1
4      WS   mary    bob         0
Run Code Online (Sandbox Code Playgroud)