0

I have a dataframe , How can i insert a row with Twith multiple values such that the index always starts with 0.

df:

   Topics_numberrs_k    Topics_assignment_k
0   0                   Int64Index([ 175, 920, 1016, 2068, 2162, 3385]
1   1                   Int64Index([ 2, 5, 6, 7, 8, 9]

Expected output:

    Topics_numberrs_k   Topics_assignment_k
0   -1                  NaN
1    0                  Int64Index([ 175, 920, 1016, 2068, 2162, 3385]
2    1                  Int64Index([ 2, 5, 6, 7, 8, 9]

2 Answers 2

1

Try:

i_row = [-1, "NaN"]

df.iloc[0] = i_row
df
Sign up to request clarification or add additional context in comments.

Comments

0

Use concat with new DataFrame and append existing:

df = pd.concat([pd.DataFrame([[-1, np.nan]], columns=df.columns), df], ignore_index=True)
print (df)
   Topics_numberrs_k                             Topics_assignment_k
0                 -1                                             NaN
1                  0  Int64Index([ 175, 920, 1016, 2068, 2162, 3385]
2                  1                  Int64Index([ 2, 5, 6, 7, 8, 9]

Or create new row and sorting index by DataFrame.sort_index, if necessary convert Topics_numberrs_k to integers:

df.loc[-1] = [-1, np.nan]

df = df.sort_index(ignore_index=True).astype({'Topics_numberrs_k':'int'})
print (df)
   Topics_numberrs_k                             Topics_assignment_k
0                 -1                                             NaN
1                  0  Int64Index([ 175, 920, 1016, 2068, 2162, 3385]
2                  1                  Int64Index([ 2, 5, 6, 7, 8, 9]

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.