I have a dataframe containing NaN
values as well as floats
我有一个包含NaN值和浮点数的数据帧
In: import pandas as pd
import numpy as np
df = pd.DataFrame([[1,np.nan],[np.nan,4]],columns=['col1','col2'],index= ['row1','row2'])
df
Out:
col1 col2
row1 1.0 NaN
row2 NaN 4.0
To extract a row, or column and fill NaN
values, I can use .fillna()
要提取行,列和填充NaN值,我可以使用.fillna()
In: df.loc[:,'col1'].fillna(99.0)
Out:
row1 1.0
row2 99.0
Name: col1, dtype: float64
But .fillna()
will not work on a single value. So I have this:
但.fillna()不会对单个值起作用。所以我有这个:
In:
if np.isnan(df.loc['row2','col1']):
val = 99.0
else:
val = df.loc['row2','col1']
val
Out: 99.0
This works, but is very clumsy compared to .fillna()
. What is the pythonic way?
这有效,但与.fillna()相比非常笨拙。什么是pythonic方式?
1 个解决方案
#1
0
df.fillna({'col1':99}, limit=1)
col1 col2
row1 1.0 NaN
row2 99.0 4.0
#1
0
df.fillna({'col1':99}, limit=1)
col1 col2
row1 1.0 NaN
row2 99.0 4.0