使用dataframe df:
Count
1
2
3
4
5
想要添加第二列,将3以上的所有内容归类为“4+” - 需要输出:
Count | Category
1 1
2 2
3 3
4 4+
5 4+
这是我的代码:
df['Category'] = df['Count']
df = df.loc[df['Count'] > 3, 'Category'] = '4+'
我收到了这个错误:
AttributeError: 'str' object has no attribute 'loc'
答案 0 :(得分:1)
请继续
df['Category'] = df['Count']
df.loc[df['Count'] > 3, 'Category'] = '4+'
答案 1 :(得分:1)
你可以试试:
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+"
输出将是:
>>> df
Count Category
0 1 1
1 2 2
2 3 3
3 4 4+
4 5 4+