我假设您在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 <= 0) | (df1.tenure > 80)]),您的数据将得到 11,即 null 值在您的 df2 中的数量(这里是 3 与我的数据)