是否有 pandas 方法通过特定列值为每一行添加数据框
Is there a pandas way to add a dataframe for each row by a specific column value
我这里有一个数据框:
name role
0 Allen Director
1 Kendrick Food
2 Sean Webmaster
3 Jacob PR
我还有另一个数据框:
power
0 eat
1 sleep
2 code
是否有 pandas 方法将 power
数据框添加到团队数据框中的每个成员,使其看起来像这样?
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
...
我试过遍历行,但我的数据框比我上面提供的示例大很多,我正在寻找 pandas 方法来执行此操作。
一个选择是assign
df2.power
到df1
作为列表,然后explode
它:
out = df1.assign(power=[df2['power'].tolist()]*len(df1)).explode('power').reset_index(drop=True)
如果你有 pandas >= 1.2.0.,你可以 cross-merge:
out = df1.merge(df2, how='cross')
输出:
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
我这里有一个数据框:
name role
0 Allen Director
1 Kendrick Food
2 Sean Webmaster
3 Jacob PR
我还有另一个数据框:
power
0 eat
1 sleep
2 code
是否有 pandas 方法将 power
数据框添加到团队数据框中的每个成员,使其看起来像这样?
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
...
我试过遍历行,但我的数据框比我上面提供的示例大很多,我正在寻找 pandas 方法来执行此操作。
一个选择是assign
df2.power
到df1
作为列表,然后explode
它:
out = df1.assign(power=[df2['power'].tolist()]*len(df1)).explode('power').reset_index(drop=True)
如果你有 pandas >= 1.2.0.,你可以 cross-merge:
out = df1.merge(df2, how='cross')
输出:
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