【问题标题】:Dataframe, creating a new column with values based on another column's indices数据框,使用基于另一列索引的值创建一个新列
【发布时间】:2020-10-11 05:16:26
【问题描述】:

我想创建一个新列,并根据索引号从第二列给它值。

数据框是df4。现有列是SalePrice,我要创建的新列是Label

我希望 Label 根据 SalePrice 的索引号有 3 个不同的值,因为 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'"

我将不胜感激!

【问题讨论】:

    标签: python pandas dataframe conditional-statements slice


    【解决方案1】:

    你快到了。您只需要放置一些括号:

    df4.loc[(df4.SalePrice.index>int(len(df4.SalePrice.index)/3)) & (df4.SalePrice.index<int(len(df4.SalePrice.index)*2/3)),"Label"]="Medium"
    

    每个语句都必须在括号中(...) &amp; (...),否则pandas无法解析过滤器。

    您还可以通过提取过滤器来重构您的代码:

        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" 
    

    通过这样做,您的代码更易于阅读。此外,这修复了您代码中的一个小错误,因为之前没有定义 == 案例。

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 2018-02-14
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多