循环遍历两个pandas数据帧

use*_*653 2 loops pandas

我有两个数据帧df1,df2如下所示:

df1:

Month    Count
6        314
6        418
6        123
7        432

df2:

Month  ExpectedValue
6       324
7       512
8       333
Run Code Online (Sandbox Code Playgroud)

我必须循环df1df2.如果df1['Month'] == 6,那么我必须循环df2以获得第6个月的预期值.然后,我将使用df1as中的字段df1['ExpectedValue'].

输出如下:

df1:

Month   Count    ExpectedValue
6        314        324 
6        418        324
6        123        324
7        432        512
Run Code Online (Sandbox Code Playgroud)

循环遍历2个数据帧是一个有效的想法吗?任何帮助,将不胜感激.

roo*_*oot 6

通常,除非绝对必要,否则不应循环使用DataFrame.使用已经优化的内置Pandas函数或使用矢量化方法,通常可以获得更好的性能.这通常会导致代码更清晰.

在这种情况下,您可以使用DataFrame.merge:

df1 = df1.merge(df2, how='left', on='Month')
Run Code Online (Sandbox Code Playgroud)

结果输出:

   Month  Count  ExpectedValue
0      6    314            324
1      6    418            324
2      6    123            324
3      7    432            512
Run Code Online (Sandbox Code Playgroud)