Add a new row to the Pandas DataFrame with a specific index name

I am trying to add a new row in a DataFrame with a specific index name 'e'.

    number   variable       values
a    NaN       bank          true   
b    3.0       shop          false  
c    0.5       market        true   
d    NaN       government    true   

I tried the following, but created a new column instead of a new row.

new_row = [1.0, 'hotel', 'true']
df = df.append(new_row)

Still don't understand how to insert a row with a specific index. We will be grateful for any suggestions.

+4
source share
2 answers

You can use df.loc[_not_yet_existing_index_label_] = new_row.

Demo:

In [3]: df.loc['e'] = [1.0, 'hotel', 'true']

In [4]: df
Out[4]:
   number    variable values
a     NaN        bank   True
b     3.0        shop  False
c     0.5      market   True
d     NaN  government   True
e     1.0       hotel   true

PS, using this method, you can not add a line to an existing (duplicated) index value (label) - a string with the mark of the index will be updated in this case.

+10
source

append , i.e

df = df.append(pd.DataFrame([new_row],index=['e'],columns=df.columns))

( @Zero)

df = df.append(pd.Series(new_row, index=df.columns), name='e') #EDIT: there was a missing ')'

:

  number    variable values
a     NaN        bank   True
b     3.0        shop  False
c     0.5      market   True
d     NaN  government   True
e     1.0       hotel   true
+3

Source: https://habr.com/ru/post/1687078/


All Articles