我有一个带有年龄的数据框 df,我正在努力将文件分类为 0 和 1 的年龄组。
df:
User_ID | Age
35435 22
45345 36
63456 18
63523 55
我尝试了以下方法
df['Age_GroupA'] = 0
df['Age_GroupA'][(df['Age'] >= 1) & (df['Age'] <= 25)] = 1
但是得到这个错误
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
为了避免它,我要使用 .loc
df['Age_GroupA'] = 0
df['Age_GroupA'] = df.loc[(df['Age'] >= 1) & (df['Age'] <= 25)] = 1
但是,这会将所有年龄标记为 1
这是我得到的
User_ID | Age | Age_GroupA
35435 22 1
45345 36 1
63456 18 1
63523 55 1
虽然这是目标
User_ID | Age | Age_GroupA
35435 22 1
45345 36 0
63456 18 1
63523 55 0
谢谢
请您参考如下方法:
由于同行压力 (@DSM),我觉得有必要分解您的错误:
df['Age_GroupA'][(df['Age'] >= 1) & (df['Age'] <= 25)] = 1
这是 chained indexing/assignment
接下来你尝试了什么:
df['Age_GroupA'] = df.loc[(df['Age'] >= 1) & (df['Age'] <= 25)] = 1
是不正确的形式,当使用 loc 时你想要:
df.loc[<boolean mask>, cols of interest] = some scalar or calculated value
像这样:
df.loc[(df['Age_MDB_S'] >= 1) & (df['Age_MDB_S'] <= 25), 'Age_GroupA'] = 1
您也可以使用 np.where 完成此操作:
df['Age_GroupA'] = np.where( (df['Age_MDB_S'] >= 1) & (df['Age_MDB_S'] <= 25), 1, 0)
要在一行中做到这一点,有很多方法可以做到这一点
