如何在具有多个数据帧的python中复制索引/匹配(具有多个标准)



我正试图在python中复制一个excel模型,以便在扩大规模时将其自动化,但我一直纠结于如何将复杂的公式转换为python。

我有三个数据帧中的信息:

DF1:

单元
ID类型1 ID类型2
a 1_a 400
b 1_b 26
c 1_c 23
1_b 45
e 1_d 24
1_b 85
g 1_a 98

对于问题的第一部分,您想对这两列进行两次左合并,如下所示:

df3 = (
df3
.merge(df1, on=['ID type 1', 'ID type 2'], how='left')
.merge(df2, on=['ID type 1', 'ID type 2'], how='left')
)
print(df3)
Date      Time ID type 1 ID type 2  Period  output  Unit   Tech
0   03/01/2022  02:30:00         a       1_a       1     254   400   wind
1   03/01/2022  02:30:00         b       1_b       1     456    26  solar
2   03/01/2022  02:30:00         c       1_c       2    3325    23    gas
3   03/01/2022  02:30:00         d       1_b       2    1254    45   coal
4   05/01/2022  02:30:00         e       1_d       3     489    24   wind
5   05/01/2022  02:30:00         a       1_a       3     452   400   wind
6   05/01/2022  02:30:00         b       1_b       4      12    26  solar
7   05/01/2022  02:30:00         c       1_c       4       1    23    gas
8   05/01/2022  03:00:00         d       1_b      35      54    45   coal
9   05/01/2022  03:00:00         e       1_d      35      48    24   wind
10  05/01/2022  03:00:00         a       1_a      48      56   400   wind

对于下一部分,您可以使用pandas.pivot_table

out = (
df3
.pivot_table(
index=['Date', 'ID type 1', 'Tech'], 
columns='Period', 
values='output', 
aggfunc=sum, 
fill_value=0)
.add_prefix('Period_')
)
print(out)

输出:

Period                      Period_1  Period_2  Period_3  Period_4  Period_35  Period_48
Date       ID type 1 Tech                                                               
03/01/2022 a         wind        254         0         0         0          0          0
b         solar       456         0         0         0          0          0
c         gas           0      3325         0         0          0          0
d         coal          0      1254         0         0          0          0
05/01/2022 a         wind          0         0       452         0          0         56
b         solar         0         0         0        12          0          0
c         gas           0         0         0         1          0          0
d         coal          0         0         0         0         54          0
e         wind          0         0       489         0         48          0

我用fill_value向你展示了这个选项,如果没有它,你会在这些单元格中得到"NaN"。

更新
根据评论中的问题,仅获取一项技术(例如"wind"(的数据透视图:

out.loc[out.index.get_level_values('Tech')=='wind']
Period                     Period_1  Period_2  Period_3  Period_4  Period_35  Period_48
Date       ID type 1 Tech                                                              
03/01/2022 a         wind       254         0         0         0          0          0
05/01/2022 a         wind         0         0       452         0          0         56
e         wind         0         0       489         0         48          0

最新更新