【问题标题】:Python Numpy Type Error: ufunc 'isfinite' not supported for the input typesPython Numpy 类型错误:输入类型不支持 ufunc \'isfinite\'
【发布时间】:2022-12-17 20:18:20
【问题描述】:

我试图编写用于创建存储桶的代码。由于要分桶的列有很多十进制值,并且是对象数据类型,所以我将该列转换为浮点型。类型转换后和运行 bins 时发生错误

这是我的代码


import pandas as pd
import numpy as np
df=pd.read_excel(r'D:\Practice Files\Anirudh Exercise Skin India.xlsx')
#print(df)

#Conversion of str to int
df['Basepacksize'] = df['Basepacksize'].astype(str).astype(float)

#Pack Ranges/Sachets/Non-Sachets
bins= ['0','10','15','30','50','100']
df1=pd.cut(df['Basepacksize'], bins)
print(df1)

我希望它能创建一个桶,但出现了这个错误

这是发生的错误

Traceback (most recent call last):
  File "C:\Users\ani\PycharmProjects\pythonProject\main7.py", line 11, in <module>
    df1=pd.cut(df['Basepacksize'], bins)
  File "C:\Users\ani\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\reshape\tile.py", line 293, in cut
    fac, bins = _bins_to_cuts(
  File "C:\Users\ani\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\reshape\tile.py", line 444, in _bins_to_cuts
    labels = _format_labels(
  File "C:\Users\ani\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\reshape\tile.py", line 578, in _format_labels
    precision = _infer_precision(precision, bins)
  File "C:\Users\ani\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\reshape\tile.py", line 644, in _infer_precision
    levels = [_round_frac(b, precision) for b in bins]
  File "C:\Users\ani\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\reshape\tile.py", line 644, in <listcomp>    levels = [_round_frac(b, precision) for b in bins]
  File "C:\Users\ani\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\reshape\tile.py", line 628, in _round_frac
    if not np.isfinite(x) or x == 0:
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Process finished with exit code 1
Improve question   

【问题讨论】:

  • 您的代码中的 x 是什么?

标签: python type-conversion bucket numpy-ufunc


【解决方案1】:

在这条线上;

if not np.isfinite(x) or x == 0:

x 的数据类型应该是 float

如果它是任何其他数据类型,它会给你错误。

【讨论】:

    猜你喜欢
    • 2020-09-29
    • 1970-01-01
    • 2020-02-16
    • 2019-11-04
    • 1970-01-01
    • 2018-01-08
    • 2018-03-09
    • 2020-07-28
    • 2021-12-01
    相关资源
    最近更新 更多