Diganta Bharali Diganta Bharali - 1 year ago 319
Python Question

ValueError: Item wrong length 907 instead of 2000

I have a csv file, that has 1000 columns. I need to read only the first 100 columns. I wrote this program for that:

import pandas as pd

list = []
for i in range (1, 100):
df = pd.read_csv('piwik_37_2016-07-08.csv',dtype = "unicode")
df = df[df.columns.isin(list)]
df.to_csv('abc.csv', index = False)

But I get error: ValueError: Item wrong length 907 instead of 2000. Can't figure out where I went wrong

Answer Source

There are a lot of things strange about your code. For example, there is no reason to iterate over the range object and update a list just to get a list of numbers. Just use list(range(1,100)).

However, if you just need the first 100 columns in the csv, there is built-in functionality for what you are trying to do:

df = pd.read_csv('piwik_37_2016-07-08.csv',dtype = "unicode", usecols = list(range(100)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download