pandas 在保存为CSV时更改NaN值的格式 [英] Pandas Changing the format of NaN values when saving to CSV

查看:38
本文介绍了 pandas 在保存为CSV时更改NaN值的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用df并使用numpy转换数据-包括将空格(或"设置为NaN).但是,当我将df写入csv时-输出包含字符串"nan",与NULL相对.

I am working with a df and using numpy to transform data - including setting blanks (or '') to NaN. But when I write the df to csv - the output contains the string 'nan' as oppose to being NULL.

我环顾四周,但找不到可行的解决方案.这是基本问题:

I have looked around but can't find a workable solution. Here's the basic issue:

df
index x    y   z
0     1   NaN  2
1     NaN  3   4

CSV输出:

index x    y   z
0     1   nan  2
1     nan  3   4

我已经尝试了一些将'nan'设置为NULL的方法,但是csv输出会导致'blank'而不是NULL:

I have tried a few things to set 'nan' to NULL but the csv output results in a 'blank' rather than NULL:

dfDemographics = dfDemographics.replace('nan', np.NaN)
dfDemographics.replace(r'\s+( +\.)|#', np.nan, regex=True).replace('', 
np.nan)
dfDemographics = dfDemographics.replace('nan', '')  # of course, this wouldn't work, but tried it anyway.

任何帮助将不胜感激.

推荐答案

要救援的熊猫,请使用 na_rep 来修复您自己的NaN表示形式.

Pandas to the rescue, use na_rep to fix your own representation for NaNs.

df.to_csv('file.csv', na_rep='NULL')

file.csv

,index,x,y,z
0,0,1.0,NULL,2
1,1,NULL,3.0,4

这篇关于 pandas 在保存为CSV时更改NaN值的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆