My DataFrame index is a tuple and I want to insert a row.
I thinked the code below would work:
df.loc[('first', 'second')] = (1, 2, 3)
But it doesn't do what I expect, instead it adds an idex 'first' and a column 'second' to a DataFrame.
My DataFrame index is a tuple and I want to insert a row.
I thinked the code below would work:
df.loc[('first', 'second')] = (1, 2, 3)
But it doesn't do what I expect, instead it adds an idex 'first' and a column 'second' to a DataFrame.
First convert index
to MultiIndex
by MultiIndex.from_tuples
, then also also add list for select columns:
df = pd.DataFrame({
'a':[1,3,5],
'b':[5,4,5],
'c':[10,11,12],
}, index= [('a','b'),('a','c'),('a','d')])
print (df)
a b c
(a, b) 1 5 10
(a, c) 3 4 11
(a, d) 5 5 12
df.index = pd.MultiIndex.from_tuples(df.index)
df.loc[('first', 'second'), ['a','b','c']] = (1,2,3)
print (df)
a b c
a b 1.0 5.0 10.0
c 3.0 4.0 11.0
d 5.0 5.0 12.0
first second 1.0 2.0 3.0