Wil*_*iam 5 python numpy dataframe pandas numpy-ndarray
我正在合并 2 个 dfs,df1 和 df2,虽然不匹配,但结果将为 Nan,但我需要它默认为 0。
df1 = pd.merge(df1, df2, left_on='MortTab', right_on='MortTab', how='left',suffixes=(' ', ''))
Run Code Online (Sandbox Code Playgroud)
现在我用这种方式将Nan转换为0:
for i in ['col1','col2','col3']: #columns that I want to check the values are NaN or not
df1[i] = np.where(df1[i].isnull(), 0, df_ia[i]) #if it's NaN, convert it to 0,or keep the same
Run Code Online (Sandbox Code Playgroud)
我手动循环每个列值来检查,如果该值是 NaN ,如果是,将其转换为 0 ,如果否保持不变。
有更好的方法吗?
您可以同样使用fillna() :
df[['col1','col2','col3']].fillna(0, inplace = True)
Run Code Online (Sandbox Code Playgroud)
您甚至可以使用类似的方法在特定列中填充特定值dict:
df.fillna({'col1':0 , 'col2':5, 'col3': 999}, inplace=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4538 次 |
| 最近记录: |