Converting NaN in dataframe to zero

≡放荡痞女 提交于 2020-05-11 07:28:21

问题


I have dictionary and created Pandas using cars = pd.DataFrame.from_dict(cars_dict, orient='index') and sorted the index (columns in alphabetical order
cars = cars.sort_index(axis=1) After sorting I noticed the DataFrame has NaN and I wasn't sure if the really np.nan values? print(cars.isnull().any()) and all column shows false.

I have tried different method to convert those "NaN" values to zero which is what I want to do but non of them is working. I have tried replace and fillna methods and nothing works Below is sample of my dataframe..

            speedtest          size 
toyota       65                NaN 
honda        77                800 

回答1:


Either use replace or np.where on the values if they are strings:

df = df.replace('NaN', 0)

Or,

df[:] = np.where(df.eq('NaN'), 0, df)

Or, if they're actually NaNs (which, it seems is unlikely), then use fillna:

df.fillna(0, inplace=True)

Or, to handle both situations at the same time, use apply + pd.to_numeric (slightly slower but guaranteed to work in any case):

df = df.apply(to_numeric, errors='coerce').fillna(0, downcast='infer')

Thanks to piRSquared for this one!



来源:https://stackoverflow.com/questions/48956789/converting-nan-in-dataframe-to-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!