Python 尝试通过使用if语句筛选另一列,在dataframe中创建新列

Python 尝试通过使用if语句筛选另一列,在dataframe中创建新列,python,pandas,dataframe,Python,Pandas,Dataframe,在我的熊猫数据框架中,尝试创建一个名为loan\u status\u的列非常好。如果贷款状态为“当前”或“已全额支付”,则应包含整数1。否则,应包含整数0 我正在使用作为我的数据集 我的问题代码是: def loan_great(): if (df['loan_status']).any == 'Current' or (df['loan_status']).any == 'Fully Paid': return 1 else: return 0 df['loa

在我的熊猫数据框架中,尝试创建一个名为loan\u status\u的列非常好。如果贷款状态为“当前”或“已全额支付”,则应包含整数1。否则,应包含整数0

我正在使用作为我的数据集

我的问题代码是:

def loan_great():
   if (df['loan_status']).any == 'Current' or (df['loan_status']).any == 'Fully Paid':
     return 1
   else:
     return 0

df['loan_status_is_great']=df['loan_status'].apply(loan_great())
TypeError回溯(最近一次调用上次) 在() ---->1 df['loan_status_is_great']=df['loan_status']。申请(loan_great())

/应用中的usr/local/lib/python3.6/dist-packages/pandas/core/series.py(self、func、convert\u dtype、args、**kwds) 4043其他: 4044 values=self.astype(object.values) ->4045 mapped=lib.map\u expert(值,f,convert=convert\u数据类型) 4046 4047如果len(映射)和isinstance(映射[0],系列):

pandas/_libs/lib.pyx在pandas中。_libs.lib.map_infere()


TypeError:“int”对象不可调用

让我们尝试另一种方法,使用
isin
创建布尔序列并转换为整数:

df['loan_status'].isin(['Current','Fully Paid']).astype(int)

我发现numpy where函数对于这些简单的列创建来说是一个很好的选择,同时保持良好的速度。类似于以下的方法应该可以工作:

import numpy as np
df['loan_status_is_great'] = np.where(df['loan_status']=='Current'|
                                      df['loan_status']=='Fully Paid',
                                      1,
                                      0)