Pandas条件:如何使用包含str的If或While语句

时间:2018-04-30 13:51:41

标签: python pandas

如何在pandas数据帧中使用str.contains()时执行条件语句。

例如,我有一个数据框,其列A包含John has a BaseballAmy has a BasketballSarah has a Tennis RacketAlex 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()

0 个答案:

没有答案