1

I want to add/update rows to a Pandas DataFrame which is multi-indexed, and the question Add one row to pandas DataFrame does not seem to address this problem. For instance, the following:

import pandas as pd


df = pd.DataFrame(columns=['x', 'y', 'z', 't'])
df.set_index(['x', 'y'])
df.loc[(1, 2), :] = [1, 3]

gives the error

KeyError: "None of [Int64Index([1, 2], dtype='int64')] are in the [index]"

By the way: is there a simpler way to initialize the DataFrame than the one above ? I tried

df = pd.DataFrame(columns=['z', 't'], index=pd.MultiIndex(names=['x', 'y']))

but this gives the error

TypeError: Must pass both levels and codes

Thanks.

Martin Gergov
  • 1,556
  • 4
  • 20
  • 29
user0
  • 185
  • 11

0 Answers0