python - 使用 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 个缺失值
感谢任何人的帮助。
解决方案
我假设你有一些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=True
以pd.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 和我的数据)
推荐阅读
- c - MPI 为其中一个进程返回不正确的结果
- vue.js - Vue Ckeditor 内容不是所见即所得
- r - 仅舍入数据框中的特定行
- javascript - javascript如何将数组规范化为正确格式的json
- javascript - 在复选框上单击 showCount 为角度 8 中的所有项目选择
- .net-core - Telerik 报告 - 无法获取报告参数
- axios - 如何使用 nuxtjs 和 axios?
- powershell - Get-ChildItem ForEach-Object 与 foreach 问题
- javascript - 错误类型错误:无法读取管道未定义的属性“toLowerCase”
- c++ - 如何将元素移动到数组的末尾