Python pandas dataframe 转换没有小数的值

Python pandas dataframe convert values without decimals

在我的数据框中,我使用以下代码将 NaN 更改为 0

df5.fillna(0, inplace=True)

但是,我得到的值是“0.0”而不是“0”。 我在这个数据框中有超过 150 列,有些需要小数,而转换为 NaN 值的列必须没有小数。我怎样才能得到那个。 我的数据框例如如下:

           genome  contig  genes    SCM  SCM/genes  TrfA_1__CP11611  \
source                                                                
20900_48    20900      48      1    0.0       0.00              NaN   
20900_37    20900      37    130  103.0       0.79              Nan   

我得到:

           genome  contig  genes    SCM  SCM/genes  TrfA_1__CP11611  \
source                                                                
20900_48    20900      48      1    0.0       0.00              0.0   
20900_37    20900      37    130  103.0       0.79              0.0  

我只需要 "NaN" 更改为“0”而不影响例如列 SCM/genes。不能选择使用带有列名的代码,因为我在此数据框中有超过 150 列带有 NaN。

谢谢

我认为您首先过滤包含 NaN 的列,然后转换这些:

In [26]:
nan_cols = df.columns[df.isnull().any(axis=0)]
nan_cols

Out[26]:
Index(['TrfA_1__CP11611'], dtype='object')

In [27]:
for col in nan_cols:
    df[col] = df[col].fillna(0).astype(int)
df

Out[27]:
          enome  contig  genes    SCM  SCM/genes  TrfA_1__CP11611
source                                                           
20900_48  20900      48      1    0.0       0.00                0
20900_37  20900      37    130  103.0       0.79                0

所以这首先查找任何行中存在的 NaN 并列出列,然后您可以遍历列并调用 fillna 并使用 [=14= 转换数据类型] 这样你 preserve/convert dtype.