2
df = pd.DataFrame({'a':[1,2,3,4],'b':[5,6,7,8],'c':[9,10,11,12]})

How can I insert a new row of zeros at index 0 in one single line? I tried pd.concat([pd.DataFrame([[0,0,0]]),df) but it did not work.

The desired output:

    a   b   c
0   0   0   0
1   1   5   9
2   2   6   10
3   3   7   11
4   4   8   12
2
  • Sorry you want to add a row of zeroes at the beginning but what should the columns be here? 'abc' or '012'? Commented Apr 28, 2016 at 20:32
  • @EdChum: Sorry, forgot to add the column names. It should be abc (edited). Commented Apr 28, 2016 at 20:33

3 Answers 3

3

You can concat the temp df with the original df but you need to pass the same column names so that it aligns in the concatenated df, additionally to get the index as you desire call reset_index with drop=True param.

In [87]:
pd.concat([pd.DataFrame([[0,0,0]], columns=df.columns),df]).reset_index(drop=True)

Out[87]:
   a  b   c
0  0  0   0
1  1  5   9
2  2  6  10
3  3  7  11
4  4  8  12
Sign up to request clarification or add additional context in comments.

Comments

2

alternatively to EdChum's solution you can do this:

In [163]: pd.DataFrame([[0,0,0]], columns=df.columns).append(df, ignore_index=True)
Out[163]:
   a  b   c
0  0  0   0
1  1  5   9
2  2  6  10
3  3  7  11
4  4  8  12

Comments

1

An answer more specific to the dataframe being prepended to

pd.concat([df.iloc[[0], :] * 0, df]).reset_index(drop=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.