python - 如何将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 新手,请您解释一下这里的问题以及如何解决它?
解决方案
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
推荐阅读
- c# - 在类之外更改类属性值
- sql - SQL 计算限制为小数点后 6 位
- cmake - CMake/FindDoxygen:MSYS2 中的路径处理
- android - 没有为“StorageUploadTask”类型定义吸气剂“未来”
- html - 我需要 Css 中 flex:1 的帮助
- python - 如何修复 Anaconda 上没有名为“PolynomialRegression”的模块?
- javascript - 获取烧瓶返回语句javascript
- c# - WPF 自定义控件:ViewBox 上的 HorizontalAlignment 样式设置未正确初始化
- react-native - 新手在这里... Firebase 和 AsyncStorage 问题
- java - ArrayList 递归行为