[英]Filling every Nan in an entire Dataframe
I'm trying to fill every blank in a dataframe. 我正在尝试填充数据框中的所有空白。
I tried: 我试过了:
df_without_nan = df.fillna("D")
#then I got an error about category so I added this
df_without_nan = df.cat.add_categories("D").fillna("D")
#cat.add only works on a series....
for column in df:
df[column] = df[column]cat.add_categories("D").fillna("D")
This is probably intuitive... help! 这可能很直观...帮助!
You are close, loop by categorical columns by DataFrame.select_dtypes
: 您关闭了,按
DataFrame.select_dtypes
的分类列DataFrame.select_dtypes
:
df = pd.DataFrame({
'A':list('abc'),
'B':[np.nan,'A','B'],
'C':[7,8,9],
'D':['X','Y', np.nan],
})
df['B'] = df['B'].astype('category')
print (df)
A B C D
0 a NaN 7 X
1 b A 8 Y
2 c B 9 NaN
#first add category to categorical columns
for column in df.select_dtypes('category'):
df[column] = df[column].cat.add_categories("D")
#then replace all NaNs
df = df.fillna("D")
print (df)
A B C D
0 a D 7 X
1 b A 8 Y
2 c B 9 D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.