将 np.nan 转换成 pd.NA

鉴于包含,我如何转换np.nan为新格式?pd.NApd.DataFramefloat


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

使用包含pd.convert_dtypes()时似乎不起作用。但是,当包含.dffloatdfint


回首忆惘然
浏览 158回答 2
2回答

偶然的你

fillna 对你有用吗?import numpy as npimport pandas as pddf = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])df.iloc[0, 1] = 1.5df.iloc[3, 0] = 4.7df = df.fillna(pd.NA)去向&nbsp; &nbsp; &nbsp; A&nbsp; &nbsp; &nbsp;B0&nbsp; <NA>&nbsp; &nbsp;1.51&nbsp; <NA>&nbsp; <NA>2&nbsp; <NA>&nbsp; <NA>3&nbsp; &nbsp;4.7&nbsp; <NA>看类型type(df.iloc[0, 0])&nbsp;出去:pandas._libs.missing.NAType

慕斯709654

从 v1.2 开始,这现在默认使用浮点数,如果你想要整数使用convert_floating=False参数。import numpy as npimport pandas as pddf = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])df.iloc[0, 1] = 1.5df.iloc[3, 0] = 4.7df = df.convert_dtypes()df.info()输出<class 'pandas.core.frame.DataFrame'>Int64Index: 4 entries, 0 to 3Data columns (total 2 columns):&nbsp;#&nbsp; &nbsp;Column&nbsp; Non-Null Count&nbsp; Dtype&nbsp;&nbsp;---&nbsp; ------&nbsp; --------------&nbsp; -----&nbsp;&nbsp;&nbsp;0&nbsp; &nbsp;A&nbsp; &nbsp; &nbsp; &nbsp;1 non-null&nbsp; &nbsp; &nbsp; Float64&nbsp;1&nbsp; &nbsp;B&nbsp; &nbsp; &nbsp; &nbsp;1 non-null&nbsp; &nbsp; &nbsp; Float64dtypes: Float64(2)memory usage: 104.0 bytes使用整数import numpy as npimport pandas as pddf = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])df.iloc[0, 1] = 1df.iloc[3, 0] = 4df = df.convert_dtypes(convert_floating=False)df.info()输出<class 'pandas.core.frame.DataFrame'>Int64Index: 4 entries, 0 to 3Data columns (total 2 columns):&nbsp;#&nbsp; &nbsp;Column&nbsp; Non-Null Count&nbsp; Dtype---&nbsp; ------&nbsp; --------------&nbsp; -----&nbsp;0&nbsp; &nbsp;A&nbsp; &nbsp; &nbsp; &nbsp;1 non-null&nbsp; &nbsp; &nbsp; Int64&nbsp;1&nbsp; &nbsp;B&nbsp; &nbsp; &nbsp; &nbsp;1 non-null&nbsp; &nbsp; &nbsp; Int64dtypes: Int64(2)memory usage: 104.0 bytes
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python