如何按多列分组,并且在 pandas 中仅包含日期时间的日期部分
How to group by multiple columns and with only date part of datetime in pandas
我有这样的数据框
CELL ID
Party
LOC
Date & Time
10631
3009787
bwp
2021-10-01 8:20:30
10631
3009787
bwp
2021-10-01 8:40:50
50987
2275172
bwp
2021-10-02 7:50:20
50987
2275172
bwp
2021-10-02 7:23:16
我想要包含分组数据的输出数据框。在组中使用 CELL ID、派对和仅日期部分的日期和时间:
以这种格式输出:https://i.stack.imgur.com/XFaDS.png
CELL ID -->Party --> 日期和时间
给你:
# df["Date & Time"] = pd.to_datetime(df["Date & Time"]) # If not already datetime
df.set_index(["CELL ID", "Party", df["Date & Time"].dt.date])
输出:
LOC Date & Time
CELL ID Party Date & Time
10631 3009787 2021-10-01 bwp 2021-10-01 08:20:30
2021-10-01 bwp 2021-10-01 08:40:50
50987 2275172 2021-10-02 bwp 2021-10-02 07:50:20
2021-10-02 bwp 2021-10-02 07:23:16
我有这样的数据框
CELL ID | Party | LOC | Date & Time |
---|---|---|---|
10631 | 3009787 | bwp | 2021-10-01 8:20:30 |
10631 | 3009787 | bwp | 2021-10-01 8:40:50 |
50987 | 2275172 | bwp | 2021-10-02 7:50:20 |
50987 | 2275172 | bwp | 2021-10-02 7:23:16 |
我想要包含分组数据的输出数据框。在组中使用 CELL ID、派对和仅日期部分的日期和时间:
以这种格式输出:https://i.stack.imgur.com/XFaDS.png
CELL ID -->Party --> 日期和时间
给你:
# df["Date & Time"] = pd.to_datetime(df["Date & Time"]) # If not already datetime
df.set_index(["CELL ID", "Party", df["Date & Time"].dt.date])
输出:
LOC Date & Time
CELL ID Party Date & Time
10631 3009787 2021-10-01 bwp 2021-10-01 08:20:30
2021-10-01 bwp 2021-10-01 08:40:50
50987 2275172 2021-10-02 bwp 2021-10-02 07:50:20
2021-10-02 bwp 2021-10-02 07:23:16