Home > Mobile >  Pandas: how to read CSV specific columns which doesn't contain header
Pandas: how to read CSV specific columns which doesn't contain header

Time:12-06

usecols = [*range(1, 5), *range(7, 9), *range(11, 13)]
df = pd.read_csv('/content/drive/MyDrive/weather.csv', header=None, usecols=usecols, names=['d', 'm', 'y', 'time', 'temp1', 'outtemp', 'temp2', 'air_pressure', 'humidity'])

I'm trying this but always get ValueError: Usecols do not match columns, columns expected but not found: [1, 2, 3, 4, 7, 8, 11, 12]

my data set looks like:

enter image description here

CodePudding user response:

The problem you are seeing is due to a mismatch in the number of columns designated by usecols and the number columns designated by names.

Usecols:

[1, 2, 3, 4, 7, 8, 11, 12]  - 8 columns

names:

'd', 'm', 'y', 'time', 'temp1', 'outtemp', 'temp2', 'air_pressure', 'humidity' - 9 columns


Change code so that the range in usecols ends in 14 rather than 13:

Code:

usecols = [*range(1, 5), *range(7, 9), *range(11, 14)]
df = pd.read_csv('/content/drive/MyDrive/weather.csv', header=None, usecols=usecols, names=['d', 'm', 'y', 'time', 'temp1', 'outtemp', 'temp2', 'air_pressure', 'humidity'])


Example df output:

enter image description here

  • Related