Pandas Insert a row above the Index and the Series data in a Dataframe
<p>I ve been around several trials, nothing seems to work so far.
I have tried <code>df.insert(0, "XYZ", 555)</code> which seemed to work until it did not for some reasons i am not certain.</p>

<p>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.</p>

<p>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.</p>

<p>Thanks for your help</p>

<p>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</p>

<pre><code>         A         B         C         D

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

0
1
2
3
4
</code></pre>

<p>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! â </p>

<p>if you want to insert a row <strong>before</strong> the first row, you can do it this way:</p>

<p>data:</p>

<pre><code>In [57]: df
Out[57]:
  id  var
0  a    1
1  a    2
2  a    3
3  b    5
4  b    9
</code></pre>

<p>adding one row:</p>

<pre><code>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
</code></pre>

<p>sort index:</p>

<pre><code>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
</code></pre>

<p>optionally reset your index    :</p>

<pre><code>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
</code></pre>

python pandas indexing dataframe row