[英]Applying function based on condition on pandas dataframe series
我是熊猫的新手
我的数据框:
df
A B
first True
second False
third False
fourth True
fifth False
期望输出
A B C
first True en
second False
third False
fourth True en
fifth False
仅当B
列为True
时,我才尝试将函数应用于列C
。
我用什么
if (df['B'] == True)):
df['C'] = df['A'].apply(
lambda x: TextBlob(x).detect_language())
但我收到一个错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我试过的
df['B'].bool()
df['B'] is True
df['B'] == 'True'
但是错误仍然存在,不确定我将如何形成一个声明,说“仅当 B 列为真”时。
谢谢你的建议。
如果在apply
仅处理具有True
s 的行之前,需要为没有匹配的行过滤行的缺失值:
df['C'] = df.loc[df['B'], 'A'].apply(lambda x: TextBlob(x).detect_language())
print (df)
A B C
0 first True en
1 second False NaN
2 third False NaN
3 fourth True en
4 fifth False NaN
或者如果需要非匹配值的空字符串,但apply
处理所有列:
df['C'] = np.where(df['B'], df['A'].apply(lambda x: TextBlob(x).detect_language()), '')
print (df)
A B C
0 first True en
1 second False
2 third False
3 fourth True en
4 fifth False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.