如何根据pandas中的列值和时间戳进行顺序计数?

2024-07-03 08:03:00 发布

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

我希望能够添加一个列,它根据值按顺序计算行数。例如,下面是三个不同的人,他们的记录有时间戳。我想根据人名来计算记录的顺序。这应该为每个PersonID重新启动。(我可以用Index()在Tableau中执行此操作,但我希望它也是原始文件的一部分)

> PersonID,             DateTime,             Order,     Total
    a226           2015-04-16 11:57:36          1          1
    a226           2015-04-17 15:32:14          2          1
    a226           2015-04-17 19:13:43          3          1
    z342           2015-04-15 07:02:20          1          1
    x391           2015-04-17 13:43:31          1          1
    x391           2015-04-17 05:12:16          2          1

有没有办法也减去日期时间?我的方法是只选择顺序1作为数据帧,然后只选择顺序2,然后合并,然后减去。有没有办法自动完成?在


Tags: 文件方法datetimeindex顺序记录时间order
3条回答

熊猫更新>;0.20:

sort()已从Pandas 0.20版本中删除(2017-05-05)。现在有sort_values()和{}。

当前运行的代码是:

df["DateTime"] = pd.to_datetime(df["DateTime"]) # just in case
df = df.sort_by(["PersonID", "DateTime"])
# Don't forget to add [] if you are grouping by more than one column!
df["Order"] = df.groupby("PersonID").cumcount() + 1

参考答案:'DataFrame' object has no attribute 'sort'

您需要使用groupby函数和sum。所以你可以尝试一下: (假设您的数据帧名为df) grouped = df.groupby("PersonID") 某些列的总和是:grouped[column].sum() 如果您只需要唯一的值,可以df["PersonID"].unique()

IIUC,你可以用^{}groupby

>>> df["Order"] = df.groupby("PersonID").cumcount() + 1
>>> df
  PersonID             DateTime  Order
0     a226  2015-04-16 11:57:36      1
1     a226  2015-04-17 15:32:14      2
2     a226  2015-04-17 19:13:43      3
3     z342  2015-04-15 07:02:20      1
4     x391  2015-04-17 13:43:31      1
5     x391  2015-04-17 05:12:16      2

如果您想保证它的时间顺序是递增的,您应该首先按DateTime排序,但是您的示例中x391是非递增的,所以我假设您不希望这样做。


如果你想让时间戳参与进来,我倾向于先排序,让生活更轻松:

^{pr2}$

但是,即使不进行排序,也可以对分组列调用rank,该列有更多选项来指定如何处理关联:

>>> df["Order"] = df.groupby("PersonID")["DateTime"].rank()
>>> df
  PersonID            DateTime  Order
0     a226 2015-04-16 11:57:36      1
1     a226 2015-04-17 15:32:14      2
2     a226 2015-04-17 19:13:43      3
5     x391 2015-04-17 05:12:16      1
4     x391 2015-04-17 13:43:31      2
3     z342 2015-04-15 07:02:20      1

相关问题 更多 >