英文:
Python - Categorise a single value yields error "Input array must be 1 dimensional"
问题
我正在尝试对单个浮点数进行分类,避免使用一系列的`if`和`elif`语句,而是使用`pd.cut`。
为什么下面的两段代码会产生错误 `Input array must be 1 dimensional`?
import pandas as pd
import numpy as np
pd.cut(0.96,bins=[0,0.5,1,10],labels=['A','B','C'])
pd.cut(np.array(0.96),bins=[0,0.95,1,10],labels=['A','B','C'])
英文:
I am trying to categorise single float numbers avoiding a list of if and elif statements using pd.cut.
Why the 2 codes below yield error Input array must be 1 dimensional?
import pandas as pd
import numpy as np
pd.cut(0.96,bins=[0,0.5,1,10],labels=['A','B','C'])
pd.cut(np.array(0.96),bins=[0,0.95,1,10],labels=['A','B','C'])
答案1
得分: 1
pd.cut操作的对象是类似数组的对象(正如它在第一个参数的文档中所述:x : array-like)。当你尝试切割单个元素时,它是一个零维数组。如果你只是在np.array调用周围加上[],你会得到你想要的结果:
>>> pd.cut(np.array([0.96]),bins=[0,0.95,1,10],labels=['A','B','C'])
['B']
Categories (3, object): ['A' < 'B' < 'C']
当你执行np.array(0.96)时,它会返回一个包含该对象的零维数组,根据np.array的文档。你也可以使用ndmin参数来强制Numpy在调用时返回一个一维数组:np.array(0.96, ndmin=1) -> array([0.96])。
英文:
pd.cut operates over an array-like object (as it states in the documentation for its first paramater: x : array-like). When you try to cut a single element, it's a 0-dimensional array. If you just say wrap [] around your np.array call, you'll get your desired result:
>>> pd.cut(np.array([0.96]),bins=[0,0.95,1,10],labels=['A','B','C'])
['B']
Categories (3, object): ['A' < 'B' < 'C']
When you do np.array(0.96), it will return a 0-dimensional array containing that object, per the documentation for np.array. You could also use the ndmin parameter to force Numpy to return a 1-dimensional array on your call: np.array(0.96, ndmin=1) -> array([0.96]).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论