简体   繁体   中英

pandas DataFrame: replace nan values with median of corresponding column

I have some NaN values in my pd dataframe and I wish to replace them with the median value of the column. I am aware that this is very similar to: pandas DataFrame: replace nan values with average of columns

However when I try the equivalent:

df = df.fillna(df.median())

I get the following error:


Python\Python37\site-packages\pandas\core\generic.py:6287: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self._update_inplace(new_data)
Python\Python37\site-packages\pandas\core\frame.py:4244: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  **kwargs

Any advice is appreciated. Thanks

Try df.fillna(df.median(axis=1, skipna=True))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM