Skip to content

BUG: Error when using usecols with names in read_csv #44147

@nancy-aggarwal

Description

@nancy-aggarwal

  • 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 master branch of pandas.

Reproducible Example

import pandas as pd

# pd.show_versions()

df = pd.DataFrame({'X': [1, 2, 3],
 'V1': [34,  6, 5],
 'V2': [4, 7, 3],
 'V3': [ 5,  56, 2]})

df.to_csv('df1.csv',index=False)

## Now read.

df_1 = pd.read_csv('df1.csv',usecols = ['X','V1','V3'],header = 0)
print(df_1)
df_2 = pd.read_csv('df1.csv',usecols = [0,1,3],header = 0,names  = ['T','V1','V3'])
print(df_2)
df_3 = pd.read_csv('df1.csv',usecols = ['X','V1','V3'],header = 0,names  = ['T','y1','y3'])
print(df_3)

Issue Description

When importing a csv into a dataframe, I want to import certain columns and rename some of them. See example below.

import pandas as pd

# pd.show_versions()

df = pd.DataFrame({'X': [1, 2, 3],
 'V1': [34,  6, 5],
 'V2': [4, 7, 3],
 'V3': [ 5,  56, 2]})

df.to_csv('df1.csv',index=False)

## Now read.

df_1 = pd.read_csv('df1.csv',usecols = ['X','V1','V3'],header = 0)
print(df_1)
df_2 = pd.read_csv('df1.csv',usecols = [0,1,3],header = 0,names  = ['T','V1','V3'])
print(df_2)
df_3 = pd.read_csv('df1.csv',usecols = ['X','V1','V3'],header = 0,names  = ['T','y1','y3'])
print(df_3)

When doing this, I get the error message that "ValueError: Usecols do not match columns, columns expected but not found: ['X']"

The code works when I don't use the names option.
The code also works when I supply the column indices to usecols instead of column names in the csv file. This is prone to human error, so I'd like to avoid it.

Expected Behavior

Expect df_3 to be created with new column names.

Installed Versions

INSTALLED VERSIONS

commit : 945c9ed
python : 3.9.7.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19042
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 12, GenuineIntel
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : English_United States.1252

pandas : 1.3.4
numpy : 1.21.3
pytz : 2021.3
dateutil : 2.8.2
pip : 21.3
setuptools : 57.4.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.2
IPython : 7.28.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.4.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.7.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions