Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding data to Pandas Dataframe from a CSV file causing Value Errors

I am trying to add an int to an existing value in a Pandas DataFrame with

>>> df.ix['index 5','Total Dollars'] += 10

I get the error: ValueError: Must have equal len keys and value when setting with an iterable.

I think the error comes from the datatype as gotten from:

>>> print type(df.ix['index 5','Total Dollars'] 
int64 <class 'pandas.core.series.Series'>

The dataframe is populated via CSV file. I tried loading the database from another CSV file:

>>> print type(df.ix['index 5','Total Dollars']
int64

What could be causing this difference in type?

like image 299
user2242044 Avatar asked Jan 29 '16 20:01

user2242044


People also ask

How do I fix parser error in pandas?

While reading a CSV file, you may get the “Pandas Error Tokenizing Data“. This mostly occurs due to the incorrect data in the CSV file. You can solve python pandas error tokenizing data error by ignoring the offending lines using error_bad_lines=False .

Is loading data from a CSV file into a pandas DataFrame?

Using the read_csv() function from the pandas package, you can import tabular data from CSV files into pandas dataframe by specifying a parameter value for the file name (e.g. pd. read_csv("filename. csv") ). Remember that you gave pandas an alias ( pd ), so you will use pd to call pandas functions.

Can you create a DataFrame from a CSV file?

Method #3: Using the csv module: One can directly import the csv files using the csv module and then create a data frame using that csv file.


1 Answers

This looks like a bug for some earlier pandas versions, fixed at least with 0.16.2 if not earlier as discussed here and here.

With 0.17.1, this works fine:

df = pd.DataFrame(data=[5], columns=['Total Dollars'], index=['index 5'])

         Total Dollars
index 5              5

df.ix['index 5', 'Total Dollars'] += 10

         Total Dollars
index 5             15
like image 185
Stefan Avatar answered Oct 21 '22 12:10

Stefan