Zulqarnain Sabir
Zulqarnain Sabir

Reputation: 75

How to group by multiple columns and with only date part of datetime in pandas

I a have dataframe like this

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

I want output dataframe which contains grouped data .Use CELL ID, Party & Only Date Part of Date & time in group :

Output in this Format : https://i.sstatic.net/XFaDS.png

CELL ID -->Party --> Date & Time

Upvotes: 1

Views: 684

Answers (1)

ddejohn
ddejohn

Reputation: 8952

Here you go:

# df["Date & Time"] = pd.to_datetime(df["Date & Time"])  # If not already datetime
df.set_index(["CELL ID", "Party", df["Date & Time"].dt.date])

Output:

                             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

Upvotes: 1

Related Questions