python - python pandas group by float range 给出 typeError
问题描述
我正在读取一个csv
文件 pandas
并希望将其分组并绘制为条形图。对于groupby
with pd.cut
,我收到以下错误(我正在关注https://stackoverflow.com/a/48280774/2005559):(实际的 csv 有很多列,其中大部分是字符串,因此read_csv
astype('float')
如果这是来源,我不能)
dataset = pd.read_csv("res.csv")
print(dataset.groupby(['IF']).size())
dataset.groupby(
pd.cut(dataset['IF'],
bins=[1, 3, 5, 7, 9, np.inf],
labels=["<1", "<3", "<5", "<7",
"<9"])).size().reset_index(name='count')
给出错误:
IF
0 23
0.29 1
0.4 7
0.51 1
0.516 1
..
9.02 2
9.16 1
9.227 1
9.3 1
9.567 2
Length: 299, dtype: int64
Traceback (most recent call last):
File "/home/rudra/Projects/Indent/init.py", line 13, in <module>
pd.cut(dataset['IF'],
File "/usr/lib64/python3.9/site-packages/pandas/core/reshape/tile.py", line 273, in cut
fac, bins = _bins_to_cuts(
File "/usr/lib64/python3.9/site-packages/pandas/core/reshape/tile.py", line 407, in _bins_to_cuts
ids = ensure_int64(bins.searchsorted(x, side=side))
TypeError: '<' not supported between instances of 'float' and 'str'
解决方案
您是否尝试过仅将此列转换为数字数据类型?
dataset['IF'] = pd.to_numeric(dataset['IF'], errors='coerce')
推荐阅读
- emacs - 在 Org 模式下导出为 PDF 时如何对齐源代码块?
- javascript - 将 html 表格数据转为在 javascript 循环中运行
- swift - 调用 stopActivityUpdates 不会停止更新
- python - 你如何简化这些循环?
- c++ - 使用 getline 通过传入智能指针参数来读取文本
- python - 序列化和反序列化 oauth2client.client.OAuth2Credentials
- javascript - 如何在 JS 画布中更改鼠标功能以触摸
- cmake - 如何制作可以使用 FIND_PACKAGE 找到的 CMake 项目?
- html - 无法从 npm 模块内联字体
- java - 使用 CipherOutputStream 进行递归加密会给出一个空字节 []