【问题标题】:Pandas find value in interval熊猫在区间中找到价值
【发布时间】:2015-01-04 21:44:57
【问题描述】:

如果我在数据帧 (transdf) 中有如下所示的事务数据,则在 pandas 中:

OrderId, ShippmentSegmentsDays
1      , 1
2      , 3
3      , 4
4      , 10

我还有另一个 df (segmentdf) 指定间隔:

ShippmentSegmentDaysStart , ShippmentSegmentDaysEnd , ShippmentSegment
-9999999                  , 0                       , 'On-Time'
0                         , 1                       , '1 day late'
1                         , 2                       , '2 days late'
2                         , 3                       , '3 days late'
3                         , 9999999                 , '>3 days late'

我需要再添加一个基于“ShippmentSegmentsDays”和“ShippmentSegment”的列。所以基本上对于“transdf”中的每一行,我需要检查“ShippmentSegmentsDays”值,其中可以从“segmentdf”中找到间隔

因此,“transdf”应如下所示:

OrderId, ShippmentSegmentsDays, ShippmentSegment
1      , 1                    , '1 day late'
2      , 0                    , 'On-Time'
3      , 4                    , '>3 days late'
4      , 10                   , '>3 days late'

谁能给我建议如何处理这种情况?

谢谢! 斯蒂芬

【问题讨论】:

标签: python pandas


【解决方案1】:

如果您知道segmentdf 中设置的规则是静态的且不会更改,则可以使用pandas.apply(args) 将函数应用于transdf 数据框中的每一行。也许下面的代码 sn-p 可以帮助你。我还没有测试过,所以要小心,但我认为它应该能让你朝着正确的方向开始。

# create a series of just the data from the 'ShippmentSegmentDays' column
seg_days_df = trends['ShippmentSegmentDays']

# Create a new column, 'ShippmentSegment', in 'transdf' data frame by calling
# our utility function on the series created above.
transdf['ShippmentSegment'] = seg_days_df.apply(calc_ship_segment, axis=1)

# Utility function to define the rules set in the 'segmentdf' data frame
def calc_ship_segment(num):
     if not num:
         return 'On Time'
     elif num == 1:
         return '1 Day Late'
     elif num == 2:
         return '2 Days Late'
     elif num == 3:
         return '3 Days Late'
     else:
         return '>3 Days Late'

【讨论】:

  • !num 不是有效的 Python 语法,我不认为。
【解决方案2】:

旧帖子,但我遇到了同样的问题。 Pandas 提供了一个对我有用的Interval function

【讨论】:

    猜你喜欢
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2021-07-06
    相关资源
    最近更新 更多