Reputation: 93
in my df i want to add row when its meets specific condition,df has thousands of rows.In id column when a new value of id is started i want to add new row copying same id value. df is as as below
id name value
0000 length 46
0000 status completed
0000 segment 21
1111 tp 0.1
1111 x 56
2222 point 23.01
2222 x 50
2222 y 40
id name value
0000 type description #new row
0000 length 46
0000 status completed
0000 segment 21
1111 type description #new row
1111 tp 0.1
1111 x 56
2222 type description #new row
2222 point 23.01
2222 x 50
2222 y 40
Upvotes: 0
Views: 49
Reputation: 195418
new = df.groupby('id', as_index=False).first().assign(name='type', value='description #new row')
df = pd.concat([new, df]).sort_values('id')
print(df)
Prints:
id name value
0 0000 type description #new row
0 0000 length 46
1 0000 status completed
2 0000 segment 21
1 1111 type description #new row
3 1111 tp 0.1
4 1111 x 56
2 2222 type description #new row
5 2222 point 23.01
6 2222 x 50
7 2222 y 40
Note: this assumes that column id
is sorted before.
Upvotes: 2