I have the following dataframe:
import pandas as pd
df = pd.DataFrame({'id':['a','b','c','d','e'],
'Sample1':[-14,-90,-90,-96,-91],
'Sample2':[-103,0,-110,-114,-114],
'Sample3':[1,2.3,3,5,6],
})
df.set_index('id', inplace=True)
df
It looks like this:
Sample1 Sample2 Sample3
id
a -14 -103 1.0
b -90 0 2.3
c -90 -110 3.0
d -96 -114 5.0
e -91 -114 6.0
I'd like to insert the following dictionary
mydict = {
"Sample1": 0.023210000000000001,
"Sample3": 0.039690000000000003,
"Sample2": 0.05824
}
mydict2 = {
"Sample1": 0.7,
"Sample3": 0.3,
"Sample2": 0.8
}
as the last column with index (row) names SRT and SRT2 .
Yielding:
Sample1 Sample2 Sample3
id
a -14 -103 1.0
b -90 0 2.3
c -90 -110 3.0
d -96 -114 5.0
e -91 -114 6.0
SRT 0.23 0.39 0.05
SRT2 0.7 0.3 0.8
How can I achieve that?
You can use loc
:
df.loc['SRT'] = pd.Series(mydict)
df.loc['SRT2'] = pd.Series(mydict2)
print (df)
Sample1 Sample2 Sample3
id
a -14.00000 -103.00000 1.00000
b -90.00000 0.00000 2.30000
c -90.00000 -110.00000 3.00000
d -96.00000 -114.00000 5.00000
e -91.00000 -114.00000 6.00000
SRT 0.02321 0.05824 0.03969
SRT2 0.70000 0.80000 0.30000
Solution with concat
:
df1 = pd.DataFrame([mydict, mydict2], index=['SRT','SRT2'])
print (df1)
Sample1 Sample2 Sample3
SRT 0.02321 0.05824 0.03969
SRT2 0.70000 0.80000 0.30000
print (pd.concat([df,df1]))
Sample1 Sample2 Sample3
a -14.00000 -103.00000 1.00000
b -90.00000 0.00000 2.30000
c -90.00000 -110.00000 3.00000
d -96.00000 -114.00000 5.00000
e -91.00000 -114.00000 6.00000
SRT 0.02321 0.05824 0.03969
SRT2 0.70000 0.80000 0.30000
using append
df.append(pd.Series(mydict, name='SRT'))
Sample1 Sample2 Sample3
id
a -14.00000 -103.00000 1.00000
b -90.00000 0.00000 2.30000
c -90.00000 -110.00000 3.00000
d -96.00000 -114.00000 5.00000
e -91.00000 -114.00000 6.00000
SRT 0.02321 0.05824 0.03969
df.append(pd.DataFrame.from_records([mydict, mydict2], ['SRT', 'SRT1']))
Sample1 Sample2 Sample3
a -14.00000 -103.00000 1.00000
b -90.00000 0.00000 2.30000
c -90.00000 -110.00000 3.00000
d -96.00000 -114.00000 5.00000
e -91.00000 -114.00000 6.00000
SRT 0.02321 0.05824 0.03969
SRT1 0.70000 0.80000 0.30000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With