Python Pandas:AttributeError:'str'对象没有属性'loc'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46328349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:29:51  来源:igfitidea点击:

Python Pandas: AttributeError: 'str' object has no attribute 'loc'

pythonstringpandaserror-handling

提问by jeangelj

Working with dataframe df:

使用数据框 df:

Count
1
2
3
4
5

Want to add second column, that categorizes everything above 3 as '4+' - needed output:

想要添加第二列,将 3 以上的所有内容归类为“4+” - 需要的输出:

Count | Category
1        1
2        2
3        3
4        4+
5        4+

This is my code:

这是我的代码:

df['Category'] = df['Count']
df = df.loc[df['Count'] > 3, 'Category'] = '4+'

And I get this error:

我收到这个错误:

AttributeError: 'str' object has no attribute 'loc'

回答by Vaishali

Just go with

随走

df['Category'] = df['Count']
df.loc[df['Count'] > 3, 'Category'] = '4+'

回答by Cedric Zoppolo

You can try out with:

你可以试试:

import pandas as pd
df = pd.DataFrame({"Count": [1,2,3,4,5]})
df["Category"] = df["Count"].apply(str)
df["Category"][df['Count'] > 3] = "4+"

Output would be:

输出将是:

>>> df
   Count Category
0      1        1
1      2        2
2      3        3
3      4       4+
4      5       4+