合并列具有默认值和覆盖的数据帧

2024-04-27 16:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,列出了各种系统的阈值:

      METRIC  SYSTEM_NAME  YELLOW      RED
16    pagins          NaN   500.0   1000.0
17  preadsec          NaN  5000.0  10000.0
18   swapins          NaN   250.0    500.0
19  cpupcent          foo   30.0     90.0
20    pagins          bar   456.0    123.0

我想将这个df合并到另一个包含这些度量的示例中。与上面的第16行和第20行一样,阈值作为一组默认值包含在配置中,并具有每个系统的覆盖

我希望这能反映在结果连接中—如果有重写,它应该优先于默认值—但是,我只能通过执行两个合并操作来看到这一点—一个用于默认值,另一个用于重写—然后第三个用于生成最终表

我相信在SQL中,我可以使用OR子句来实现这一点,但在Pandas中找不到这样做的方法

这样的事情存在吗

编辑:为清楚起见,另一个DF有以下结构:

              SYSTEM_NAME    METRIC        CVAL
19886                 foo  cpupcent   89.281734
19887                 bar   swapins   41.799927
19888                 bar    pagins   123.92355
19889                quux  preadsec   28.837423
19890                quux    pagins   232.30303

因此,在假设的合并中,结果输出如下所示:

              SYSTEM_NAME    METRIC        CVAL   YELLOW      RED
19886                 foo  cpupcent   89.281734     30.0     90.0
19887                 bar   swapins   41.799927    250.0    500.0
19888                 bar    pagins   123.92355    456.0    123.0
19889                quux  preadsec   28.837423   5000.0  10000.0 
19890                quux    pagins   232.30303    500.0   1000.0

在这里,bar的pagins被覆盖,而qux采用黄色和红色的默认值。由于替代仅适用于分页,因此默认情况下为栏的交换


Tags: namefoo系统bar阈值rednanmetric
1条回答
网友
1楼 · 发布于 2024-04-27 16:36:00

我发现了这个。这有点复杂和混乱,但它解决了一个合理的时间框架的问题

它假设这些值通过一个附加列进行加权,优先选择最小值

# Ground work, prepare the index
tmp_df = df.reset_index()
# Now, perform the merge. Use the common value, then tidy up the duplicates
tmp_df = tmp_df.merge(t_df, 'left', on='METRIC')\
         .drop('SYSTEM_NAME_y', axis=1)
         .rename(index=str, columns='SYSTEM_NAME_x':'SYSTEM_NAME'})
         .drop_duplicates(subset=['END_DATE','METRIC','SYSTEM_NAME'], keep='last')
# And restore the index
tmp_df = tmp_df.set_index(df.index.name)

相关问题 更多 >