Home > other >  Dataframe add new row if the index does not exist like a dictionary without checking existence
Dataframe add new row if the index does not exist like a dictionary without checking existence

Time:05-14

import pandas as pd
a = [['a', 1, 2, 3], ['b', 4, 5, 6], ['c', 7, 8, 9]]
df = pd.DataFrame(a, columns=['alpha', 'one', 'two', 'three'])
df.set_index(['alpha'], inplace = True)
       one  two  three
alpha                 
a        1    2      3
b        4    5      6
c        7    8      9

I want to set some values for example:

df.loc['a']['one'] = 1000

and when the index does not exist, we add a new row with this index without checking the existence just like dictionary (if the key does not exsit dict[new key] will automatically create this key). For example:

df.loc['d']['three'] = 999

Then there will be a new row:

d: Nan, Nan, 999

Following code does not work for me:

df.loc['d']['three'] = 999

enter image description here

CodePudding user response:

This is exactly what pandas does, but you need to use the loc indexer correctly:

df.loc['a', 'one'] = 1000
df.loc['d', 'three'] = 999

output:

          one  two  three
alpha                    
a      1000.0  2.0    3.0
b         4.0  5.0    6.0
c         7.0  8.0    9.0
d         NaN  NaN  999.0
  • Related