【问题标题】:Data Lost while creating bins using python pandas cut function使用 python pandas cut 函数创建 bin 时数据丢失
【发布时间】:2019-06-20 14:50:18
【问题描述】:

我的目标是将一列从 df1 转移到 df2 并同时创建 bin。我有名为 df1 的数据框,其中包含 3 个数值变量。我想将一个名为“tenure”的变量提取到 df2 并希望创建 bin。它将列值传输到 df2 但 df2 显示了一些缺失值。 请在下面找到代码:

df2=pd.cut(df1["tenure"] , bins=[0,20,60,80], labels=['low','medium','high'])

在创建 df2 之前,我检查了 df1 中的缺失值。没有这样混乱的值,但在创建 bin 后它显示 11 个缺失值。

print(df2.isnull().sum())

上面的代码显示了 11 个缺失值

感谢任何人的帮助。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我假设您在df1['tenure'] 中有一些不在(0,80] 中的值,可能是零。请看下面的例子:

    df1 = pd.DataFrame({'tenure':[-1, 0, 12, 34, 78, 80, 85]})
    print (pd.cut(df1["tenure"] , bins=[0,20,60,80], labels=['low','medium','high']))
    
    0       NaN    # -1 is lower than 0 so result is null
    1       NaN    # it was 0 but the segment is open on the lowest bound so 0 gives null
    2       low
    3    medium
    4      high
    5      high    # 80 is kept as the segment is closed on the right
    6       NaN    # 85 is higher than 80 so result is null
    Name: tenure, dtype: category
    Categories (3, object): [low < medium < high]
    

    现在,您可以在pd.cut 中传递参数include_lowest=True 以保持结果中的左边界:

    print (pd.cut(df1["tenure"] , bins=[0,20,60,80], labels=['low','medium','high'],
                  include_lowest=True))
    
    0       NaN
    1       low  # now where the value was 0 you get low and not null
    2       low
    3    medium
    4      high
    5      high
    6       NaN
    Name: tenure, dtype: category
    Categories (3, object): [low < medium < high]
    

    所以最后,我认为如果您打印 len(df1[(df1.tenure &lt;= 0) | (df1.tenure &gt; 80)]),您的数据将得到 11,即 null 值在您的 df2 中的数量(这里是 3 与我的数据)

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2018-08-19
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多