【问题标题】:shifting up the column basis groupby向上移动列 basis groupby
【发布时间】:2022-11-23 16:07:44
【问题描述】:

现有数据框:

Id       event      time_spent_in_sec
A         in               0
A         step_1           2.2
A         step_2           3
A         done             3
B          in              0
B         step_1           5
B         step_2           8
B         step_3           15
B         done             7

预期数据框:

Id       event      time_spent_in_sec
A         in               2.2
A         step_1           3
A         step_2           3
A         done             0
B          in              5
B         step_1           8
B         step_2           15
B         step_3           7
B         done             0

我希望移动列中的值time_spent_in_sec并用 0 填充每个唯一 ID 的最后一行。

我尝试使用 shift(1) 但坚持用 0 填充最后一行

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用.fillna() 将其填充为原始的第一个数字:

    df.time_spent_in_sec.shift(-1).fillna(df.time_spent_in_sec[0])
    

    或者:

    df.time_spent_in_sec.shift(-1, fill_value = df.time_spent_in_sec[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 2019-10-01
      • 1970-01-01
      • 2023-04-06
      • 2014-04-20
      • 2016-01-21
      • 1970-01-01
      • 2016-09-15
      相关资源
      最近更新 更多