我希望从dataframe的第一部分添加行到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我想将Circle行添加到其他形状中(但将值circle替换为其各自的形状,无论是正方形还是三角形),使其如下所示:
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有没有一种简单的方法可以通过group by或merge来做到这一点?
发布于 2021-11-02 18:08:58
尝试:
# circle rows
circles = df.query('Type=="Circle"')
pd.concat([df] + [circles.assign(Type=t) for t in df.Type.unique() if t!='Circle'])输出:
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 2Dhttps://stackoverflow.com/questions/69814968
复制相似问题