首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向Dataframe的部分添加行

向Dataframe的部分添加行
EN

Stack Overflow用户
提问于 2021-11-02 17:59:51
回答 1查看 29关注 0票数 0

我希望从dataframe的第一部分添加行到dataframe的其他部分,同时更改一列中的值。

例如,如果我将以下内容作为我的输入数据帧:

代码语言:javascript
复制
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替换为其各自的形状,无论是正方形还是三角形),使其如下所示:

代码语言:javascript
复制
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来做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2021-11-02 18:08:58

尝试:

代码语言:javascript
复制
# circle rows
circles = df.query('Type=="Circle"')

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

输出:

代码语言:javascript
复制
       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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69814968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档