-2

Before writing my output dataframe to an excel file, I need to add an extra row to my dataframe. Below is my example dataframe:

    -----------------------------
    | Col1 | Col2 | Col3 | Col4 |
    -----------------------------
0   | CA1  | CB1  | CC2  | CD1  |
1   | CA5  | CB5  | CC5  | CD5  |
2   | CA3  | CB3  | CC3  | CD3  |
    -----------------------------

mydict= {'Col1': 'P', 'Col2': 'Q', 'Col3': 'R', 'Col4': 'S'}

Now I need to add an extra row where new row values should be picked from mydict corresponding to column header.

Desired Output:

    -----------------------------
    | Col1 | Col2 | Col3 | Col4 |
    -----------------------------
    |  P   |  Q   |  R   | S    |
0   | CA1  | CB1  | CC2  | CD1  |
1   | CA5  | CB5  | CC5  | CD5  |
2   | CA3  | CB3  | CC3  | CD3  |
    -----------------------------

Can anyone please help.

Rtut
  • 937
  • 3
  • 11
  • 19
  • Possible duplicate of [How to add an extra row to a pandas dataframe](http://stackoverflow.com/questions/19365513/how-to-add-an-extra-row-to-a-pandas-dataframe) – David Jun 22 '16 at 18:43
  • My question is different. I need to add a new row at index 2. If I do it this way, it will overwrite existing row? Also wanted to know how to get values from mydict for corresponding column headers. Thanks. – Rtut Jun 22 '16 at 18:45
  • I'm confused... Is that your desired output? Are you looking to insert a row at a desired location or get multiple names for each column? – michael_j_ward Jun 22 '16 at 18:52

1 Answers1

0

Will this work for you? First, convert mydict to a dataframe and then use pd.concat

mydict = mydict= {'Col1': 'P', 'Col2': 'Q', 'Col3': 'R', 'Col4': 'S'}
df1 = pd.DataFrame(data=mydict, index=[0])

data = np.array([['CA1', 'CB1', 'CC2', 'CD1'],
                 ['CA5', 'CB5', 'CC5', 'CD5'],
                 ['CA3', 'CB3', 'CC3', 'CD3']])
df2 = pd.DataFrame(data, columns=['Col1', 'Col2', 'Col3', 'Col4'])

new_df = pd.concat([df1, df2])

Then new_df is

In [58]: new_df
Out[58]: 
  Col1 Col2 Col3 Col4
0    P    Q    R    S
0  CA1  CB1  CC2  CD1
1  CA5  CB5  CC5  CD5
2  CA3  CB3  CC3  CD3
lanery
  • 5,222
  • 3
  • 29
  • 43