0
df.head(7)
df

Month,ward1,ward2,...ward30
    Apr-19, 20, 30,   45
    May-19, 18, 25,   42
    Jun-19, 25, 19,   35
    Jul-19, 28, 22,   38
    Aug-19, 24, 15,   40
    Sep-19, 21, 14,   39
    Oct-19, 15, 18,   41

to:

Month, ward1
Apr-19, 20  
May-19, 18  
Jun-19, 25  
Jul-19, 28  
Aug-19, 24  
Sep-19, 21  
Oct-19, 15  

Month,ward2 
Apr-19, 30  
May-19, 25  
Jun-19, 19  
Jul-19, 22  
Aug-19, 15  
Sep-19, 14  
Oct-19, 18  

Month, ward30
Apr-19, 45
May-19, 42
Jun-19, 35
Jul-19, 38
Aug-19, 40
Sep-19, 39
Oct-19, 41

How to group-by date wise in python using pandas?

I have dataframe df that contains a datetime and 30 other columns which I want to split by date attached with each of those columns in pandas but I am facing some difficulties.

Hamza
  • 5,373
  • 3
  • 28
  • 43

3 Answers3

0

try using a dictionary comprehension to hold your separate dataframes.

dfs = {col : df.set_index('Month')[[col]] for col in (df.set_index('Month').columns)}

print(dfs['ward1'])

        ward1
Month        
Apr-19     20
May-19     18
Jun-19     25
Jul-19     28
Aug-19     24
Sep-19     21
Oct-19     15

print(dfs['ward30'])

        ward30
Month         
Apr-19      45
May-19      42
Jun-19      35
Jul-19      38
Aug-19      40
Sep-19      39
Oct-19      41
Umar.H
  • 22,559
  • 7
  • 39
  • 74
  • @BHAVESHSADHU don't forget to accept this answer if it solved your solution so this can be closed. best of luck :) – Umar.H Nov 12 '20 at 16:03
0

One straight forward way would be to set date column as index and separating out every other column:

data.set_index('Month', inplace =True)
data_dict = {col: data[col] for col in data.columns}
Hamza
  • 5,373
  • 3
  • 28
  • 43
-1

You have to create new DataFrames:

data1 = pd.DataFrame()
data1['Month'] = df['Month']
data1['ward1'] = df['ward1']
data1.head()
Alona
  • 67
  • 1
  • 10