python - Pandas pd.cut ValueError:值的长度与索引的长度不匹配
问题描述
我有一个具有相同行数的数据框和系列。
的结果pd.cut
也输出具有相同形状的数据。
我哪里错了?
我的数据框,37459 行:
df.shape
(37459, 124)
我要剪切的列,37459 行:
df['score']
2 74.390244
4 29.268293
5 45.121951
6 46.341463
7 31.707317
...
43502 21.951220
43503 1.219512
43505 3.658537
43506 8.536585
43507 12.195122
Name: score, Length: 37459, dtype: float64
以及 pd.cut 的输出:
pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)
(2 3
4 1
5 2
6 2
7 1
..
43502 1
43503 1
43505 1
43506 1
43507 1
Name: score, Length: 37459, dtype: category
Categories (3, int64): [1 < 2 < 3], array([ 0, 33, 66, 100]))
我尝试将结果附加pd.cut
到 df. 我试图将其分成三组并标记它们[1,2,3]
:
df['score_cut'] = pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)
ValueError: Length of values does not match length of index
我哪里错了?
解决方案
retbins=True
让pd.cut()
你返回一个元组。(请参阅文档。)
df['score_cut'], bins = pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)
应该管用
推荐阅读
- web - 为已发布二进制文件的公共存储库寻找解决方案,可使用 wget 工具恢复
- laravel - Laravel Lumen 雄辩的左连接返回连接表数据而不是主数据
- python - Snakemake 使用所有样本作为 porechop 的一个输入
- python - Dict:按多个键+降序/升序排序
- gdb - 在 gdb 中运行带有全屏选项(例如 pudb)的 python 脚本失败
- python - 在 Windows 10 Powershell 上使用 Python 3.9.2 在 VS Code 中的源 Pylance 无法解析/无法解析导入
- python - Airflow + Dask:任务环境识别
- apache - 是否可以在将处理程序添加到 Apache conf 文件之前检查它是否存在?
- python - 在嵌套列表中查找多个重复项,然后在保留最新条目的同时删除它们
- perl - 关于 Perl 映射函数的建议