0
import seaborn as sns
import missingno as msno 
import matplotlib.pylab as plt 
from sklearn.impute import SimpleImputer 

titanic = sns.load_dataset("titanic") 

imputer_embark_town = SimpleImputer(strategy="most_frequent") 
imputer_age = SimpleImputer(strategy="median") 

titanic["embark_town"] = imputer_embark_town.fit_transform(titanic[["embark_town"]]) 
titanic["age"] = imputer_embark_town.fit_transform(titanic[["age"]]) 

in this code,
titanic["embark_town"] = imputer_embark_town.fit_transform(titanic[["embark_town"]])
line throw an error, but next line is no problem.

Error Massage

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File c:\users\lg\.spyder-py3\temp.py:11
    titanic["embark_town"] = imputer_embark_town.fit_transform(titanic[["embark_town"]])

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py:3950 in __setitem__
    self._set_item(key, value)

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py:4143 in _set_item
    value = self._sanitize_column(value)

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py:4871 in _sanitize_column
    return sanitize_array(value, self.index, copy=True, allow_2d=True)

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\construction.py:569 in sanitize_array
    subarr = maybe_infer_to_datetimelike(data)

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\dtypes\cast.py:1196 in maybe_infer_to_datetimelike
    raise ValueError(value.ndim)  # pragma: no cover

ValueError: 2

If I change the line using .ravel() method, No Error.

import seaborn as sns
import missingno as msno 
import matplotlib.pylab as plt 
from sklearn.impute import SimpleImputer 

titanic = sns.load_dataset("titanic") 

imputer_embark_town = SimpleImputer(strategy="most_frequent") 
imputer_age = SimpleImputer(strategy="median") 

titanic["embark_town"] = imputer_embark_town.fit_transform(titanic[["embark_town"]]) .ravel()
titanic["age"] = imputer_embark_town.fit_transform(titanic[["age"]])

What's difference between two lines?

titanic["embark_town"] = imputer_embark_town.fit_transform(titanic[["embark_town"]])
titanic["age"] = imputer_embark_town.fit_transform(titanic[["age"]])

I think the first and second lines of the code are structurally the same, so why does only the first line produce an error?

나기훈
  • 9
  • 1

0 Answers0