【问题标题】:Calculate a third column based on two other columns values for iteration on a fourth column根据其他两列值计算第三列以在第四列上进行迭代
【发布时间】:2022-01-01 10:28:59
【问题描述】:

[结果]

[输入数据]

我在 Python 中有一个数据框: 我想通过以下方式计算每个“产品订单”的“开始”和“结束”列的减法: 对于每个产品编号,我都有“类型”A 到 D:我需要从每个产品订单的 A 开始时间中减去 D 的结束时间。知道怎么做吗?谢谢。

输入数据:

process order   Type   Start   End
111               A     10      20
111               B     22      25
111               C     28       30
111               D     33       35 
222               A     37       40
222               B     42       45
222
222
333
333
333
333

类似于流程订单 111:我们有 D (End: 35) - A (Strat: 10) = 25 输出应该是这样的:

process order   Time_difference
111             25
222              ?
333              ?

【问题讨论】:

  • 请将您的数据粘贴为表格/代码,而不是屏幕截图。还包括您尝试过的任何代码。
  • 请以文本形式提供数据
  • 如何选择应该减去起始列的哪个值?我知道它们是黄色的,但是当您从 excel 文件加载数据框时,颜色将不存在。

标签: python pandas dataframe lambda iteration


【解决方案1】:

按您的订单分组,然后从最后一行中取出 end 值,然后从第二行中减去 start 值:

df.groupby('order_number').apply(lambda x: x.iloc[-1, 'end'] - x.iloc[1, 'start'])

如果需要,您可以将这些结果重新加入到原始 df

【讨论】:

    【解决方案2】:

    假设所有产品都有 A 到 F 类型,请尝试:

    #sort values so that B is the 2nd and F is the last row for each order number
    df = df.sort_values(["order number", "type"])
    
    #groupby order number and keep the 2nd (iat[1]) row for "start" and the last row for "end"
    output = df.groupby("order number").agg({"start": lambda x: x.iat[1], "end": "last"})
    
    #compute the difference
    diff = output["end"] - output["start"]
    
    >>> diff
    order number
    103895166    2072
    103900419    2228
    103902156    9348
    dtype: int64
    
    输入df:
        order number type  start    end
    0      103895166    A      0   1999
    1      103895166    B    361   2067
    2      103895166    C    365   2117
    3      103895166    D    368   2118
    4      103895166    E    497   2423
    5      103895166    F    498   2433
    6      103900419    A      0   3627
    7      103900419    B   2128   3791
    8      103900419    C   2132   3841
    9      103900419    D   2135   3842
    10     103900419    E   2264   4346
    11     103900419    F   2454   4356
    12     103902156    A      0  12432
    13     103902156    B   3852  12938
    14     103902156    C   3856  12987
    15     103902156    D   3860  13000
    16     103902156    E   3864  13100
    17     103902156    F   3868  13200
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      相关资源
      最近更新 更多