Reputation: 4498
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'
Upvotes: 3
Views: 28055
Reputation: 4743
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+
Upvotes: 1
Reputation: 38415
Just go with
df['Category'] = df['Count']
df.loc[df['Count'] > 3, 'Category'] = '4+'
Upvotes: 6