Grouping dataframe on the basis of fields entered by user on runtime and time intervals

Viewed 29

I have dataframe consists of 3 columns : sitename, circle, time and count. I need to group dataframe based on multiple columns within interval of every 10 min.

df.head(20)
Out[87]: 
   SITENAME CIRCLE                Time  count
0      OC01     C2 2020-09-01 00:01:00      1
1      OC02     C1 2020-09-01 00:04:00      1
2      OC02     C1 2020-09-01 00:07:00      1
2      OC02     C1 2020-09-01 00:07:00      1
3      OC01     C2 2020-09-01 00:08:00      1
4      OC02     C1 2020-09-01 00:09:00      1
5      OC02     C1 2020-09-01 00:10:00      1
6      OC02     C1 2020-09-01 00:13:00      1
7      OC02     C1 2020-09-01 00:14:00      1
8      OC01     C2 2020-09-01 00:16:00      1
9      OC03     C2 2020-09-01 00:17:00      1
10     OC03     C2 2020-09-01 00:17:00      1
11     OC04     C1 2020-09-01 00:18:00      1
12     OC01     C2 2020-09-01 00:18:00      1
13     OC02     C1 2020-09-01 00:24:00      1
14     OC01     C2 2020-09-01 00:26:00      1
15     OC02     C1 2020-09-01 00:30:00      1
16     OC03     C2 2020-09-01 00:31:00      1
17     OC03     C2 2020-09-01 00:31:00      1
18     OC03     C2 2020-09-01 00:31:00      1
19     OC03     C2 2020-09-01 00:31:00      1

When I am doing this by below command, it working fine:

print(df.groupby(['SITENAME','CIRCLE',pd.Grouper(key='Time', freq='10T', axis =0)])['count'].sum())

Output:

SITENAME  CIRCLE  Time               
OC01      C2      2020-09-01 00:00:00     2
                  2020-09-01 00:10:00     2
                  2020-09-01 00:20:00     1
                  2020-09-01 00:30:00     1
OC02      C1      2020-09-01 00:00:00     3
                  2020-09-01 00:10:00     3
                  2020-09-01 00:20:00     1
                  2020-09-01 00:30:00     3
                  2020-09-01 00:40:00     4
                  2020-09-01 00:50:00     4
OC03      C2      2020-09-01 00:10:00     2
                  2020-09-01 00:30:00    48
OC04      C1      2020-09-01 00:10:00     1
                  2020-09-01 00:30:00    17

But, we I am taking input from user with multiple fields it is not working:

inp = input('Enter Columns(in case of multiple columns, use , as sep): ')
inp
Out[92]: 'SITENAME,CIRCLE'

when I am using below command it is giving error:

print(df.groupby([inp.split(","),pd.Grouper(key='Time', freq='10T', axis =0)])['count'].sum())

ValueError: Grouper and axis must be same length

I have also tried to add input and pd.Grouper(key='Time', freq='10T', axis =0) in list and then use that list in groupby, but it didn't work.

print(df.groupby(list(inp))['count'].sum())
1 Answers

Use + for append to one element list like:

df.groupby(inp.split(",") + [pd.Grouper(key='Time', freq='10T', axis =0)])
Related