简体   繁体   中英

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

Working with dataframe df:

Count
1
2
3
4
5

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

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+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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