Laskii
Laskii

Reputation: 31

Add Rows to Section of Dataframe

I'm looking to add rows from first section of dataframe to other sections of the dataframe while changing the value in one column.

For example if I have this as my input dataframe:

Type     Color    Size    Dimensions
Circle   Blue     Large   2D
Circle   Green    Small   3D
Circle   Black    Large   2D
Square   Red      Large   2D
Square   White    Small   3D
Triangle Red      Large   2D
Triangle White    Small   3D

I want to add the Circle rows to the other shapes (but replace the value circle with its respective shape, either square or triangle) so it looks like this:

Type     Color    Size    Dimensions
Circle   Blue     Large   2D
Circle   Green    Small   3D
Circle   Black    Large   2D
Square   Red      Large   2D
Square   White    Small   3D
Square   Blue     Large   2D
Square   Green    Small   3D
Square   Black    Large   2D
Triangle Red      Large   2D
Triangle White    Small   3D
Triangle Blue     Large   2D
Triangle Green    Small   3D
Triangle Black    Large   2D

Is there a simple way to do this via group by or merge?

Upvotes: 0

Views: 44

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Try:

# circle rows
circles = df.query('Type=="Circle"')

pd.concat([df] + [circles.assign(Type=t) for t in df.Type.unique() if t!='Circle'])

Output:

       Type  Color   Size Dimensions
0    Circle   Blue  Large         2D
1    Circle  Green  Small         3D
2    Circle  Black  Large         2D
3    Square    Red  Large         2D
4    Square  White  Small         3D
5  Triangle    Red  Large         2D
6  Triangle  White  Small         3D
0    Square   Blue  Large         2D
1    Square  Green  Small         3D
2    Square  Black  Large         2D
0  Triangle   Blue  Large         2D
1  Triangle  Green  Small         3D
2  Triangle  Black  Large         2D

Upvotes: 1

Related Questions