简体   繁体   English

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

[英]Python Pandas: AttributeError: 'str' object has no attribute 'loc'

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'

Just go with 随便去吧

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

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+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM