[英]Trying to make a new column in pandas dataframe by filtering another column using a if statement
Trying to make a column named loan_status_is_great on my pandas dataframe.试图在我的 pandas dataframe 上创建一个名为 loan_status_is_great 的列。 It should contain the integer 1 if loan_status is "Current" or "Fully Paid."如果loan_status 是“当前”或“全额支付”,它应该包含integer 1。 Else it should contain the integer 0.否则它应该包含 integer 0。
I'm using https://resources.lendingclub.com/LoanStats_2018Q4.csv.zip as my dataset.我使用https://resources.lendingclub.com/LoanStats_2018Q4.csv.zip作为我的数据集。
My problem code is:我的问题代码是:
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 Traceback (most recent call last) in () ----> 1 df['loan_status_is_great']=df['loan_status'].apply(loan_great()) () 中的 TypeError Traceback (最近一次调用最后一次) ----> 1 df['loan_status_is_great']=df['loan_status'].apply(loan_great())
/usr/local/lib/python3.6/dist-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds) 4043 else: 4044 values = self.astype(object).values -> 4045 mapped = lib.map_infer(values, f, convert=convert_dtype) 4046 4047 if len(mapped) and isinstance(mapped[0], Series): /usr/local/lib/python3.6/dist-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds) 4043 else: 4044 values = self.astype(object)。 values -> 4045 mapped = lib.map_infer(values, f, convert=convert_dtype) 4046 4047 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer() pandas._libs.lib.map_infer() 中的 pandas/_libs/lib.pyx
TypeError: 'int' object is not callable类型错误:'int' object 不可调用
Let's try a different approach using isin
to create a boolean series and convert to integer:让我们尝试一种不同的方法,使用isin
创建 boolean 系列并转换为 integer:
df['loan_status'].isin(['Current','Fully Paid']).astype(int)
I find that the numpy where function is a good choice for these simple column creations while maintaining good speed.我发现 numpy 其中 function 是这些简单列创建的不错选择,同时保持良好的速度。 Something like the below should work:像下面这样的东西应该可以工作:
import numpy as np
df['loan_status_is_great'] = np.where(df['loan_status']=='Current'|
df['loan_status']=='Fully Paid',
1,
0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.