'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
Solution 1:[1]
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
Solution 2:[2]
Something like this
ddf=[]
for i in range(len(df.columns)/3):
ddf.append(df[df.columns[3*i:3*i+3]])
to generate a list df of dataframes, each with 3 columns.
Add the rest (with less than 3 columns):
ddf.append(df[df.columns[3*(i+1):]])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
