首页 > 解决方案 > 使用 python pandas cut 函数创建 bin 时数据丢失

问题描述

我的目标是将一列从 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 中的缺失值。没有这样混乱的值,但在创建垃圾箱后,它显示了 11 个缺失值。

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

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

感谢任何人的帮助。

标签: pythonpandasdataframe

解决方案


我假设你有一些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]

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

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 <= 0) | (df1.tenure > 80)])你会得到 11 和你的数据作为你的null值的数量df2(这里是 3 和我的数据)


推荐阅读