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]
CodePudding user response:
Try:
i_row = [-1, "NaN"]
df.iloc[0] = i_row
df
CodePudding user response:
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]