Python – Categorise a single value yields error "Input array must be 1 dimensional"
Question:
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'])
Answers:
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])
.
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'])
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])
.