1

I have a dataframe:

df = pd.DataFrame({'a':[1,2,3,4,5],'b':[100,200,300,400,500],'c':['a','b','j','e','q']})   
df = df.set_index(['a','b'])  #(this is sample structure, i will be having directly the indexed df)

       c
a  b     
1 100  a
2 200  b
3 300  j
4 400  e
5 500  q

This is my input multi-indexed dataframe

I have 3 variables:

a1 = 7
b1 = 700
c1 = z

(a1,b1)   c

i want to add this as a new row to the multi-indexed dataframe, without unsetting the index and then re-creating.

Final result also as a multi-indexed dataframe.

Final output required.

       c
a  b     
1 100  a
2 200  b
3 300  j
4 400  e
5 500  q
7 700  z

One way is to unset the index first, append the row, and then re-create the index.( but the actual size of my df will be around 1 million) so this might affect performance.

Is it possible to add row to multi-indexed dataframe apart from the method mentioned above?

1 Answer 1

1

You can use if this combination does not exist in original MultiIndex:

df.loc[(a1,b1), 'c'] = c1
print (df)
       c
a b     
1 100  a
2 200  b
3 300  j
4 400  e
5 500  q
7 700  z

If combination exist original value is overwritten:

a1 = 1
b1 = 100
c1 = 'z'
df.loc[(a1,b1), 'c'] = c1
print (df)
       c
a b     
1 100  z # a to z
2 200  b
3 300  j
4 400  e
5 500  q
Sign up to request clarification or add additional context in comments.

1 Comment

Didnt't think it was this simple! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.