[英]Is there a pandas way to add a dataframe for each row by a specific column value
I have a dataframe here:我这里有一个 dataframe:
name role
0 Allen Director
1 Kendrick Food
2 Sean Webmaster
3 Jacob PR
I also have another dataframe:我还有一个 dataframe:
power
0 eat
1 sleep
2 code
Is there a pandas way to add the power
dataframe to each member in the team dataframe to make it look like this?有没有一种 pandas 方法可以将 dataframe 的
power
添加到团队 dataframe 中的每个成员,使其看起来像这样?
name role power
0 Allen Director eat
1 Allen Director sleep
2 Allen Director code
3 Kendrick Food eat
4 Kendrick Food sleep
5 Kendrick Food code
...
I've tried doing by iterating through the rows but my dataframe is a lot larger than the example I have provided above and I am looking for a pandas approach to do this.我尝试通过遍历行来完成,但我的 dataframe 比我上面提供的示例大很多,我正在寻找 pandas 方法来执行此操作。
One option is to assign
df2.power
to df1
as a list, then explode
it:一种选择是
assign
df2.power
作为列表分配给df1
,然后将其explode
:
out = df1.assign(power=[df2['power'].tolist()]*len(df1)).explode('power').reset_index(drop=True)
If you have pandas >= 1.2.0., you can cross-merge:如果你有 pandas >= 1.2.0.,你可以交叉合并:
out = df1.merge(df2, how='cross')
Output: Output:
name role power
0 Allen Director eat
1 Allen Director sleep
2 Allen Director code
3 Kendrick Food eat
4 Kendrick Food sleep
5 Kendrick Food code
6 Sean Webmaster eat
7 Sean Webmaster sleep
8 Sean Webmaster code
9 Jacob PR eat
10 Jacob PR sleep
11 Jacob PR code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.