我在条件语句中使用 if,如下面的代码。如果地址是 NJ,则名称列的值将更改为“N/A”。
df1.loc[df1.Address.isin(['NJ']), 'name'] = 'N/A'
如果我有如下所示的“嵌套 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'
我可以使用 df.loc
实现上述逻辑吗?或者还有其他方法吗?
最佳答案
单独分配,as shown @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
关于python - 在 pandas/python 中嵌套带有 .loc 的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50031277/