Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split dataframe vertically, having N columns in each resulting DF

I have the following dataframe:

Date     2017-12-05 2017-12-06 2017-12-15 2017-12-19 2017-12-20  2017-12-21   ....
time                                                                         
00:00:00      19.94      21.19      21.88      20.76      21.26      21.26   
00:15:00      20.29      21.07      21.71      21.79      21.95      21.52   
00:30:00      21.03      21.25      21.80      22.15      22.26      21.62   
00:45:00      22.20      21.56      22.77      22.20      22.33      21.91   
01:00:00      23.25      22.15      23.71      22.31      22.69      21.99   
01:15:00      23.78      23.33      24.53      22.29      22.82      22.58

Columns are dates, and I want to split the dataframe by every 3 date columns. How can I do this?

Illustration of the final result with one of the resultant dataframes following the split:

Date      2017-12-05 2017-12-06 2017-12-15 2
     time                                                                         
     00:00:00      19.94      21.19      21.88      
     00:15:00      20.29      21.07      21.71      
     00:30:00      21.03      21.25      21.80      
     00:45:00      22.20      21.56      22.77      
     01:00:00      23.25      22.15      23.71      
     01:15:00      23.78      23.33      24.53
like image 267
jerry han Avatar asked Oct 23 '25 04:10

jerry han


1 Answers

you can use np.split(..., axis=1):

In [157]: N = 3

In [158]: dfs = np.split(df, np.arange(N, len(df.columns), N), axis=1)

In [159]: dfs[0]
Out[159]:
          2017-12-05  2017-12-06  2017-12-15
00:00:00       19.94       21.19       21.88
00:15:00       20.29       21.07       21.71
00:30:00       21.03       21.25       21.80
00:45:00       22.20       21.56       22.77
01:00:00       23.25       22.15       23.71
01:15:00       23.78       23.33       24.53

In [160]: dfs[1]
Out[160]:
          2017-12-19  2017-12-20  2017-12-21
00:00:00       20.76       21.26       21.26
00:15:00       21.79       21.95       21.52
00:30:00       22.15       22.26       21.62
00:45:00       22.20       22.33       21.91
01:00:00       22.31       22.69       21.99
01:15:00       22.29       22.82       22.58
like image 200
MaxU - stop WAR against UA Avatar answered Oct 25 '25 17:10

MaxU - stop WAR against UA