Skip to content

BUG: KeyError when loading csv with NaNs #56929

@CYHSM

Description

@CYHSM

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

# Define parameters for data
nan_rows = 3
random_rows = 7
total_rows = nan_rows + random_rows

# With two levels
level1 = ['Level 1'] * 1  
level2 = ['Level 2'] * 1 

# Combine these lists to create a MultiIndex for columns
columns = pd.MultiIndex.from_arrays([level1, level2], names=['level1', 'level2'])

# Create dummy data
data = np.random.rand(total_rows, len(columns))
data[:nan_rows, :] = np.nan 
df_complex = pd.DataFrame(data, columns=columns)

# Save the DataFrame as a CSV
csv_filename_complex = 'example_data_complex.csv'
df_complex.to_csv(csv_filename_complex)

# Load the data back with header=[0, 1] and index_col=0
loaded_df_complex = pd.read_csv(csv_filename_complex, header=[0, 1], index_col=0)

# NaN in row 0 is ommited:
print(loaded_df_complex.head(total_rows))

# Also throws a KeyError when indexing into it
try:
    loaded_df_complex.loc[0]
    print('Works')
except KeyError:
    print('Does not work')

Issue Description

When loading back a CSV file previously saved using pandas, the first row is omitted if it contains NaN values. The problem seems to be the default behaviour for replacing NaN with ''. If we force replacement to be 'NaN' the same example works, see below:

Maybe related Issue: #55803

Expected Behavior

# Define parameters for data
nan_rows = 3
random_rows = 7
total_rows = nan_rows + random_rows

# With two levels
level1 = ['Level 1'] * 1  
level2 = ['Level 2'] * 1 

# Combine these lists to create a MultiIndex for columns
columns = pd.MultiIndex.from_arrays([level1, level2], names=['level1', 'level2'])

# Create dummy data
data = np.random.rand(total_rows, len(columns))
data[:nan_rows, :] = np.nan 
df_complex = pd.DataFrame(data, columns=columns)

# Save the DataFrame as a CSV
csv_filename_complex = 'example_data_complex.csv'
df_complex.to_csv(csv_filename_complex, na_rep='NaN')

# Load the data back with header=[0, 1] and index_col=0
loaded_df_complex = pd.read_csv(csv_filename_complex, header=[0, 1], index_col=0)

# NaN in row 0 is not ommited:
print(loaded_df_complex.head(total_rows))

# Also throws a KeyError when indexing into it
try:
    loaded_df_complex.loc[0]
    print('Works')
except KeyError:
    print('Does not work')

Installed Versions

INSTALLED VERSIONS

commit : 0f43794
python : 3.8.16.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.0-91-generic
Version : #101~20.04.1-Ubuntu SMP Thu Nov 16 14:22:28 UTC 2023
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.0.3
numpy : 1.24.3
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.8.0
pip : 23.1.2
Cython : 3.0.0
pytest : 7.4.0
hypothesis : None
sphinx : 7.1.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.12.2
pandas_datareader: None
bs4 : 4.12.2
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.7.1
numba : None
numexpr : 2.8.4
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.10.1
snappy : None
sqlalchemy : None
tables : 3.8.0
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : 2.4.1
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIO CSVread_csv, to_csvMissing-datanp.nan, pd.NaT, pd.NA, dropna, isnull, interpolate

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions