user1559897
user1559897

Reputation: 1484

What is wrong with adding a row to pandas dataframe like this?

I am creating a simple dataframe like the following.

cache_df = pd.DataFrame(columns=['ticker', 'maturity', 'rate', 'datetime'])
cache_df = cache_df.set_index(['ticker', 'maturity'])

When I try to add a row, i am getting an error that i couldnt wrap my mind around. Can anyone help me understand why?

cache_df.loc[symbolName, expiry] = [rate, updateTime]

I got

ValueError: cannot set using a multi-index selection indexer with a different length than the value

and my dataframe looks strange after the error message.

Out[106]: 
                rate datetime  2016-11-18 00:00:00
ticker maturity                                   
GECC             NaN      NaN                  NaN

if I do

cache_df.loc[[1,2]] = [3,4]

I get a different error:

ValueError: zero-size array to reduction operation maximum which has no identity

Upvotes: 1

Views: 893

Answers (1)

user1559897
user1559897

Reputation: 1484

Okay, after spending nearly two hours googling for possible causes, I figured out why. The problem is with multi-indexing. I guess a more helpful error message could be used here.

With a multi-indexed dataframe, the loc needs to be explicit.

The following code solves the issue.

cache_df.loc[(symbolName, expiry), :] = [rate, updateTime]

Upvotes: 1

Related Questions