首页 > 解决方案 > 如何将Series字符串与python中的另一个字符串进行比较

问题描述

我正在尝试将 Series 中的字符串与 Python 中的字符串进行比较。这里似乎没问题 - 我得到了真假结果:

domains_types['subtype'].astype(str) == 'Default'

对于文件: 打印(域类型)

但是当我尝试在“if”中使用它时,出现了一些问题: ValueError: The truth value of a Series is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

if domains_types['subtype'].astype(str) == 'Default':
    domains_types['Category'] = 'e-commerce'
else:
    domains_types['Category'] = 'other'

我是 Python 新手,请您解释一下这里的问题以及如何解决它?

我想根据 我想要的“sybtype”结果添加一个带有“类别”的新列,这里只有“其他”类别

标签: pythonstringcomparison

解决方案


def cat(val):
    if val == 'Default':
        return('e-commerce')
    else:
        return('other')

df['Category'] = df.apply(lambda x: cat(x['Subtype']), axis=1)

这应该根据子类型列中每个值的值返回“其他”或“电子商务”。上面解释了对整个系列进行等效检查的问题。

或者,如果您想使用“正常” for 循环,您可以遍历数据框,例如:

newcol = []

for index, row in df.iterrows():
    if row.Subtype == 'Default':
        newcol.append('e-commerce')
    else:
        newcol.append('other')

df['Category'] = newcol

推荐阅读