值迭代和更新列值时出错

2024-09-20 23:01:39 发布

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

我有两个具有相同列名的数据帧,需要同时遍历这两个数据帧,以查看是否有重叠,是否有日期重叠,如果有,则更新数据帧中与内部循环关联的一列。你知道吗

我目前能够确定是否有重叠,但无法更新值和获取值错误。你知道吗

4月19日副本

cmdb    type            begin                end             duration   
xyz Planned Outage  2019-03-31 09:45:00 2019-03-31 11:27:00   12291 
xyz Planned Outage  2019-04-20 07:25:00 2019-04-22 10:50:00  185100 

19年4月

cmdb type           begin             end           duration    
xyz Outage  2019-04-30 15:20:00 2019-05-01 00:17:00   32279 
xyz Outage  2019-04-20 21:42:00 2019-04-20 21:43:00      60  

我试过使用itertuples,iterrows等等,但都没有用。你知道吗

from datetime import datetime
from collections import namedtuple
Range = namedtuple('Range', ['begin', 'end'])

for item in apr19_copy.itertuples():
    r1 = Range(begin = item.begin, end = item.end)
    for item_outage in apr19.itertuples():
        r2 = Range(begin = item_outage.begin,  end = item_outage.end)
        latest_start = max(r1.begin,  r2.begin)
        earliest_end = min(r1.end,  r2.end)
        if(latest_start > earliest_end):
            continue
        diff = (earliest_end - latest_start).seconds + 1
        overlap = max(0, diff)
        print(item_outage.duration)
        apr19.set_value(item_outage.index, 'duration',  item_outage.duration 
                                                        - overlap)

在运行上述代码段之后,我希望apr19数据帧的第二行中的duration设置为0。结果数据帧应如下所示(请注意*在预期值附近)

19年4月

cmdb type           begin             end           duration    
xyz Outage  2019-04-30 15:20:00 2019-05-01 00:17:00   32279 
xyz Outage  2019-04-20 21:42:00 2019-04-20 21:43:00      *0*     

但是我得到

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Tags: 数据typerangeitemenddurationr2begin
1条回答
网友
1楼 · 发布于 2024-09-20 23:01:39

错误是由item_outage.index引起的。它是从itertuples获得的,index表示它上面的一个方法。要获取行的索引,必须使用Index。所以你应该使用:

    apr19.set_value(item_outage.Index, 'duration',  item_outage.duration 
                                                    - overlap)

但是我的pandas版本给了我一个使用set_value的贬损警告,所以我认为这应该更好(如果你的pandas版本接受的话):

    apr19.at[item_outage.Index, 'duration'] = item_outage.duration - overlap

它可以工作,但值不是预期的0而是-1。。。你知道吗

相关问题 更多 >

    热门问题