【问题标题】:Shift happens: using pandas shift to combine rowsShift 发生:使用 pandas shift 来组合行
【发布时间】:2019-03-21 00:28:44
【问题描述】:

我正在尝试在 pandas 中的数据框中添加一列,其中每个条目表示相邻两行中另一列值之间的差异(如果满足某些条件)。按照对get previous row's value and calculate new column pandas python 的回答,我使用shift 来查找两行中duration_seconds 列条目之间的增量(下一个减去当前),然后如果两行都来自相同的行,则将该增量作为派生条目返回user_id,下一行的action 不是“登录”,增量不是负数。代码如下:

def duration (row):
    candidate_duration = row['duration_seconds'].shift(-1) - row['duration_seconds']
    if row['user_id'] == row['user_id'].shift(-1) and row['action'].shift(-1) != 'login' and candidate_duration >= 0:
        return candidate_duration
    else:
        return np.nan

然后我用

测试这个函数
analytic_events.apply(lambda row: duration(row), axis = 1)

但这会引发错误:

AttributeError: ("'int' object has no attribute 'shift'", '发生在索引 9464384')

我想知道这是否类似于已修复的错误 here,因此我尝试传入整个数据框:

duration(analytic_events)

但这会引发错误:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我应该怎么做才能实现这种组合;我应该如何使用shift

【问题讨论】:

  • 是否可以添加示例数据框和预期输出?
  • 我希望没有那个@Erfan,它会是自我解释的,这可能是我犯的一个愚蠢的错误。但我可以试试(真实数据庞大且私密)
  • 样本数据总是有助于理解陈述。 :)

标签: pandas


【解决方案1】:

没有看到您的数据。您可以通过使用np.where 有条件地创建列来简化此操作:

cond1 = analytic_events['user_id'] == analytic_events['user_id'].shift(-1)   
cond2 = analytic_events['action'].shift(-1) != 'login'
cond3 = analytic_events['duration_seconds'].shift(-1) - analytic_events['duration_seconds'] >= 0

analytic_events['candidate_duration'] = np.where((cond1) & (cond2) & (cond3), 
                                                 analytic_events['duration_seconds'].shift(-1) - analytic_events['duration_seconds'], 
                                                 np.NaN)

解释 np.where 作用如下:np.where(condition, value if true, value is false)

【讨论】:

  • 嗯。当您说“简化”时,您可以说“修复”。我不确定为什么你的有效而我的原版无效。 (注意,我的收获——再次——不要使用apply!)
猜你喜欢
  • 1970-01-01
  • 2017-08-25
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多