我创建了一个函数来创建新列。在返回值时,它给出了错误
“DataFrame”对象没有“数据不可用”属性
示例 df:
col1 col2
abc 10
def 20
ghi 30
功能:
def fun1():
if (df['col1'].isin(['xyz'])).any():
output=df.loc[df['col1']=='xyz',['col2']]
return output
else:
output = "data not available"
return output
调用函数如下:
df['new_column'] = df.apply(fun1(),axis=1)
当我调用函数时,我遇到了上述错误。我已经搜索过它,但无法找到解决方案。出了什么问题?
尝试:
def fun1(val):
if (val['col1'] in 'xyz'):
return val['col2']
else:
return "data not available"
最后:
df['new_column'] = df.apply(fun1,axis=1)
注意:您可以apply()
通过以下方式降低成本:
df['new_column']=df['col2'].where(df['col1'].eq('xyz'),"data not available")
或者
#import numpy as np
df['new_column']=np.where(df['col1'].eq('xyz'),df['col2'],"data not available")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句