简体   繁体   中英

Convert np.nan to pd.NA

How can I convert np.nan into the new pd.NA format, given the pd.DataFrame comprises float ?

import numpy as np
import pandas as pd

df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])
df.iloc[0, 1] = 1.5
df.iloc[3, 0] = 4.7

df = df.convert_dtypes()

type(df.iloc[0, 0])  # numpy.float64 - I'am expecting pd.NA

Making use of pd.convert_dtypes() doesn't seem to work when df comprises float . This conversion is however working fine when df contains int .

Will fillna work for you?

import numpy as np
import pandas as pd

df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])
df.iloc[0, 1] = 1.5
df.iloc[3, 0] = 4.7

df = df.fillna(pd.NA)

df

      A     B
0  <NA>   1.5
1  <NA>  <NA>
2  <NA>  <NA>
3   4.7  <NA>

Look at type

type(df.iloc[0, 0]) 

Out:

pandas._libs.missing.NAType

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