Pythus Pythus - 2 months ago 17
Python Question

Pandas Insert a row above the Index and the Series data in a Dataframe

I ve been around several trials, nothing seems to work so far.
I have tried

df.insert(0, "XYZ", 555)
which seemed to work until it did not for some reasons i am not certain.

I understand that the issue is that Index is not considered a Series and so, df.iloc[0] does not allow you to insert data directly above the Index column.

I ve also tried manually adding in the list of indices part of the definition of the dataframe a first index with the value "XYZ"..but nothing has work.

Thanks for your help

A B C D are my columns. range(5) is my index. I am trying to obtain this below, for an arbitrary row starting with type, and then a list of strings..thanks

A B C D

type 'string1' 'string2' 'string3' 'string4'

0
1
2
3
4


If you use Timestamps as Index adding a row and a custom single row with its own custom index will throw an error:
ValueError: Cannot add integral value to Timestamp without offset. I am guessing it's due to the difference in the operands, if i substract an Integer from a Timestamp for example.. ? how could i fix this in a generic manner? thanks! –

Answer

if you want to insert a row before the first row, you can do it this way:

data:

In [57]: df
Out[57]:
  id  var
0  a    1
1  a    2
2  a    3
3  b    5
4  b    9

adding one row:

In [58]: df.loc[df.index.min() - 1] = ['z', -1]

In [59]: df
Out[59]:
   id  var
 0  a    1
 1  a    2
 2  a    3
 3  b    5
 4  b    9
-1  z   -1

sort index:

In [60]: df = df.sort_index()

In [61]: df
Out[61]:
   id  var
-1  z   -1
 0  a    1
 1  a    2
 2  a    3
 3  b    5
 4  b    9

optionally reset your index :

In [62]: df = df.reset_index(drop=True)

In [63]: df
Out[63]:
  id  var
0  z   -1
1  a    1
2  a    2
3  a    3
4  b    5
5  b    9
Comments