Why is Pandas DataFrame.loc different for a DataFrame with two columns as index?

Viewed 19

I am having trouble adding a row to a pandas DataFrame with two columns as index. This is the code I'm using:

df = pd.DataFrame(columns=['id', 'idx1', 'val'])
df = df.set_index(['id', 'idx1'])
df.loc[123, 'a'] = [1]

Then df becomes:

          val  a
id  idx1        
123       NaN  1

However, I expect to get this:

          val 
id  idx1        
123    a   1

When I change the length of the index to three (or one), I get what I expect. For example, if I run this code:

df = pd.DataFrame(columns=['id', 'idx1', 'idx2', 'val'])
df = df.set_index(['id', 'idx1', 'idx2'])
df.loc[123, 'a', 'b'] = [1]

df becomes:

               val
id  idx1 idx2     
123 a    b       1

Is there something different when referring to two columns as index?

1 Answers

Your dataframe is empty. Only index and column names are defined. So how should Pandas know what you mean by df.loc[123, 'a'] = 1?

  • create an entry with the first index 123 and a column 'a', or
  • use 123 and 'a' as two levels of a multiindex?

Solution:

df.loc[(123, 'a'), 'val'] = 1
Related