我想创建一个新列,并根据索引号从第二列为其提供值。
数据帧为df4
。现有列为SalePrice
,我要创建的新列为Label
。
我希望Label
具有3个不同的值,具体取决于SalePrice
的索引号,因为SalePrice
是根据其值排序的。
这是我的处理方式:
df4.loc[df4.SalePrice.index<int(len(df4.SalePrice.index)/3),"Label"]="Expensive"
df4.loc[df4.SalePrice.index>int(len(df4.SalePrice.index)/3),"Label"]="medium"
df4.loc[df4.SalePrice.index>int(len(df4.SalePrice.index)*2/3),"Label"]="Low"
所以这行得通,但我认为可能会有更有效,更好的方法...我尝试在第二个命令行中使用范围
df4.loc[df4.SalePrice.index>int(len(df4.SalePrice.index)/3)& df4.SalePrice.index<int(len(df4.SalePrice.index)*2/3),"Label"]="Medium"
但是我得到:
"TypeError: unsupported operand type(s) for &: 'int' and 'RangeIndex'"
我会很感激的答案!
答案 0 :(得分:0)
您快到了。您只需要放置一些括号即可:
df4.loc[(df4.SalePrice.index>int(len(df4.SalePrice.index)/3)) & (df4.SalePrice.index<int(len(df4.SalePrice.index)*2/3)),"Label"]="Medium"
每个语句都必须放在括号(...) & (...)
中,否则熊猫无法解析过滤器。
您还可以通过提取过滤器来重构代码:
mask_expensive = df4.SalePrice.index < int(len(df4.SalePrice.index)/3)
mask_low = df4.SalePrice.index > int(len(df4.SalePrice.index)*2/3)
mask_medium = (~ mask_expensive) & (~ mask_low)
df4.loc[mask_expensive,"Label"]="Expensive"
df4.loc[mask_medium ,"Label"]="medium"
df4.loc[mask_low,"Label"]="Low"
这样做,您的代码更易于阅读。此外,这还修复了代码中的一个小错误,因为==
大小写之前没有定义。