pd.set_option("styler.format.na_rep", "NULL") 和 pd.options.styler.format.na_rep = "NULL" 不起作用

问题描述 投票:0回答:1
In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.set_option("styler.format.na_rep", "NULL")

In [4]: df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
   ...:                    'mask': ['red', 'purple'],
   ...:                    'weapon': [np.nan, np.nan]})

In [5]: df.to_csv("temp.csv", index=False)

输出

temp.csv

name,mask,weapon
Raphael,red,
Donatello,purple,

csv 最后一列应为“NULL”。

pd.options.styler.format.na_rep = "NULL"
也不起作用。

我不想将

na_rep
设置为
to_csv
参数,非常希望它是全局的。

Pandas v2.2.2(最新),使用 pyenv 二进制文件的 Python 3.10.12。

我测试了

na_rep
模块是否被突破
to_csv
to_csv
工作正常,将
np.nan
替换为
NULL

python-3.x pandas
1个回答
0
投票

pd.options.styler.format.na_rep
style 相关,适用于 HTML 或 Excel 格式,不适用于文本/CSV。

例如,在笔记本中,

df
不显示格式:

enter image description here

但是

df.style
确实:

enter image description here

然而,虽然

df.style
to_html
to_excel
方法,但它没有
to_csv

一种解决方法可能是使用默认的

to_csv
:
 创建另一个 
na_ref='NULL'

方法
from pandas.core.base import PandasObject

def to_csv_null(df, *args, **kwargs):
    return df.to_csv(*args, na_rep='NULL', **kwargs)

PandasObject.to_csv_null = to_csv_null

df.to_csv_null('temp.csv', index=False)

输出:

name,mask,weapon
Raphael,red,NULL
Donatello,purple,NULL
© www.soinside.com 2019 - 2024. All rights reserved.