如何在pandas数据帧中使用str.contains()
时执行条件语句。
例如,我有一个数据框,其列A
包含John has a Baseball
,Amy has a Basketball
,Sarah has a Tennis Racket
和Alex has a Football
字样。
我想这样做:
if df[df['A].str.contains('Ball')]
然后从包含Ball
&的句子中提取名称字符串。将其分配给新列Name
所需的结果是新名称'要包含的列:John,Amy&亚历
我的实际代码如下:
if df[df['A'].str.contains('Anon')] == 'True':
df['Name'] = df['A'].str.split(' ').str[0]
这给了我错误:
TypeError: Could not compare ['True'] with block values
我也尝试过:
if df[df['A'].str.contains('Anon')] == True:
df['Name'] = df['A'].str.split(' ').str[0]
这给了我错误:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()