Skip to content

BUG: None becomes empty string when writing multiple columns to CSV, but double quotes "" when writing single columns #59116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
2 of 3 tasks
mvashishtha opened this issue Jun 26, 2024 · 3 comments
Labels
Bug Closing Candidate May be closeable, needs more eyeballs IO CSV read_csv, to_csv

Comments

@mvashishtha
Copy link

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

df = pd.DataFrame([['a', 0], [None, 1]], columns=['col0', 'col1'])

df.to_csv('all_columns.csv', index=False, columns=['col0', 'col1'])
print(f'CSV from writing all columns:\n{open("all_columns.csv").read()}')

df.to_csv('first_column.csv', index=False, columns=['col0'])
print(f'CSV from writing all columns:\n{open("first_column.csv").read()}')

Issue Description

The None in the dataframe becomes an empty string when writing both columns, but "" when writing just the first column.

Expected Behavior

Should be consistent and use the representation for missing data in na_rep in both cases.

Installed Versions

versions
INSTALLED VERSIONS
------------------
commit                : bdc79c146c2e32f2cab629be240f01658cfb6cc2
python                : 3.9.19.final.0
python-bits           : 64
OS                    : Darwin
OS-release            : 23.5.0
Version               : Darwin Kernel Version 23.5.0: Wed May  1 20:14:38 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6020
machine               : arm64
processor             : arm
byteorder             : little
LC_ALL                : None
LANG                  : en_US.UTF-8
LOCALE                : en_US.UTF-8

pandas                : 2.2.1
numpy                 : 1.26.4
pytz                  : 2024.1
dateutil              : 2.8.2
setuptools            : 68.2.2
pip                   : 23.3.1
Cython                : None
pytest                : 7.4.4
hypothesis            : None
sphinx                : 7.3.7
blosc                 : None
feather               : None
xlsxwriter            : None
lxml.etree            : None
html5lib              : None
pymysql               : None
psycopg2              : None
jinja2                : 3.1.3
IPython               : 8.12.0
pandas_datareader     : None
adbc-driver-postgresql: None
adbc-driver-sqlite    : None
bs4                   : None
bottleneck            : None
dataframe-api-compat  : None
fastparquet           : None
fsspec                : 2024.3.1
gcsfs                 : None
matplotlib            : 3.8.4
numba                 : None
numexpr               : None
odfpy                 : None
openpyxl              : 3.1.2
pandas_gbq            : None
pyarrow               : 16.0.0
pyreadstat            : None
python-calamine       : None
pyxlsb                : None
s3fs                  : None
scipy                 : 1.13.0
sqlalchemy            : None
tables                : None
tabulate              : 0.9.0
xarray                : None
xlrd                  : None
zstandard             : None
tzdata                : 2024.1
qtpy                  : None
pyqt5                 : None
@mvashishtha mvashishtha added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jun 26, 2024
@asishm
Copy link
Contributor

asishm commented Jun 26, 2024

The current pandas behavior matches python stdlib csv. The reason quoting becomes necessary is to distinguish a 1-element row with the single empty field from an empty row.

In [64]: with StringIO() as f:
    ...:     writer = csv.writer(f)
    ...:     writer.writerow(['col0'])
    ...:     writer.writerow(['a'])
    ...:     writer.writerow([None])
    ...:     f.seek(0)
    ...:     print(f.read())
    ...:
col0
a
""

Setting writer = csv.writer(f, quoting=csv.QUOTE_NONE) raises with Error: single empty field record must be quoted

xref: #18676
xref cpython: python/cpython#76436

@Aloqeely Aloqeely added IO CSV read_csv, to_csv Closing Candidate May be closeable, needs more eyeballs and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Jun 27, 2024
@Siddharth-Latthe-07
Copy link

@mvashishtha try this updated code, which ensures consistency, specify the na_rep parameter in to_csv method. This parameter determines how missing values are represented in the CSV file.

import pandas as pd

df = pd.DataFrame([['a', 0], [None, 1]], columns=['col0', 'col1'])

df.to_csv('all_columns.csv', index=False, columns=['col0', 'col1'], na_rep='NaN')
print(f'CSV from writing all columns:\n{open("all_columns.csv").read()}')

df.to_csv('first_column.csv', index=False, columns=['col0'], na_rep='NaN')
print(f'CSV from writing first column:\n{open("first_column.csv").read()}")

Hope this helps, plz let me know if it works
Thanks

@taranarmo
Copy link
Contributor

Maybe pandas should warn users when they write a single column csv with None values? This behavior isn't intuitive and looks inconsistent with the case of multiple columns even though it follows the csv.writer logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Closing Candidate May be closeable, needs more eyeballs IO CSV read_csv, to_csv
Projects
None yet
Development

No branches or pull requests

5 participants