Man*_*ary 2 python missing-data dataframe pandas fillna
问候大家。我有一个 excel 文件,我需要根据列数据类型清理和填充 NaN 值,例如,如果列数据类型是对象,我需要在该列中填充“NULL”,如果数据类型是整数或浮点数,则需要填充 0在那些列中。
到目前为止,我已经尝试了 2 种方法来完成这项工作,但没有运气,这是第一个
df = pd.read_excel("myExcel_files.xlsx")
Run Code Online (Sandbox Code Playgroud)
df.select_dtypes(include='int64').fillna(0, inplace=True)
df.select_dtypes(include='float64').fillna(0.0, inplace=True)
df.select_dtypes(include='object').fillna("NULL", inplace=True)
Run Code Online (Sandbox Code Playgroud)
我得到的输出不是错误而是警告,数据框没有变化
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py:4259: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
**kwargs
Run Code Online (Sandbox Code Playgroud)
df = pd.read_excel("myExcel_files.xlsx")
#get the list of all integer columns
int_cols = list(df.select_dtypes('int64').columns)
#get the list of all float columns
float_cols = list(df.select_dtypes('float64').columns)
#get the list of all object columns
object_cols = list(df.select_dtypes('object').columns)
#looping through if each column to fillna
for i in int_cols:
df[i].fillna(0,inplace=True)
for f in float_cols:
df[f].fillna(0,inplace=True)
for o in object_cols:
df[o].fillna("NULL",inplace=True)
Run Code Online (Sandbox Code Playgroud)
我的两种方法都不行。非常感谢您的任何帮助或建议。问候 -马尼什
我认为,而不是使用select_dtypes和迭代列,您可以使用.dtypesDF 并将 float64 的 0.0 和对象替换为“NULL”……您无需担心 int64,因为它们通常不会缺少值填充(除非您正在使用pd.NA或可为空的 int 类型),因此您可以执行以下单个操作:
df.fillna(df.dtypes.replace({'float64': 0.0, 'O': 'NULL'}), inplace=True)
Run Code Online (Sandbox Code Playgroud)
您还可以添加,downcast='infer'以便如果列中有可以是int64s 的内容float64,则以int64s结尾,例如给出:
df = pd.DataFrame({
'a': [1.0, 2, np.nan, 4],
'b': [np.nan, 'hello', np.nan, 'blah'],
'c': [1.1, 1.2, 1.3, np.nan]
})
Run Code Online (Sandbox Code Playgroud)
然后:
df.fillna(df.dtypes.replace({'float64': 0.0, 'O': 'NULL'}), downcast='infer', inplace=True)
Run Code Online (Sandbox Code Playgroud)
会给你(注意列a被向下转换为 int 但c仍然浮动):
a b c
0 1 NULL 1.1
1 2 hello 1.2
2 0 NULL 1.3
3 4 blah 0.0
Run Code Online (Sandbox Code Playgroud)