ValueError: Data must not be constant

Viewed 2011

I am trying to transform my data using boxcox transformation. As there's the value 0 I consider the following approach found in ValueError: Data must be positive (boxcox scipy) But now i am getting value error says Data must not be constant. Here's my approach:

posdata = df1[df1['hotel'] > 0]['hotel']
bcdata, lam = boxcox(posdata)
bc = np.empty_like(df1['hotel'])
bc[df1['hotel'] > 0] = bcdata
bc[df1['hotel'] == 0] = -1/lam 

I get this error:

ValueError                                Traceback (most recent call last)
<ipython-input-163-551b3ccca575> in <module>
  1 posdata = df1[df1['hotel'] > 0]['hotel']
  2 bcdata, lam = boxcox(posdata)
  3 bc = np.empty_like(df1['hotel'])
  4 bc[df1['hotel'] > 0] = bcdata
  5 bc[df1['hotel'] == 0] = -1/lam

  ~\AppData\Roaming\Python\Python37\site-packages\scipy\stats\morestats.py in boxcox(x, lmbda, alpha)
  1040 
  1041     if np.all(x == x[0]):
  1042         raise ValueError("Data must not be constant.")
  1043 
  1044     if any(x <= 0):

  ValueError: Data must not be constant.
1 Answers

Use sklearn and reshape your data in column vector:

from sklearn.preprocessing import PowerTransformer

fit = PowerTransformer(
   method = 'box-cox',
   scale = False,
)

transform = fit.fit(
   np.array(data).reshape(-1, 1)
)

Related