I have a pd.Series with, for instance, n lines. I would like to transform this series in a pd.DataFrame as follows:


Input: pd.Series([10,11,12,13,14,15]) and a variable chunk_size = 2 that will be the number of columns.


    0 | 1
    _   _
    10  11
    12  13
    14  15

The target DataFrame will have a shape of (n / chunk_size) rows by chunk_size columns.

Thanks in advance.


Here is a quick solution that does not do it in-place but takes up extra space:

def transform_series(x, chunk_size):
    df = pd.DataFrame()
    for i in range(chunk_size):
        df[f'column_{i+1}'] = x[i::chunk_size].reset_index(drop=True)
    return df

input_series = pd.Series([10,11,12,13,14,15])
transformed_df = transform_series(input_series, chunk_size=2)



   column_1  column_2
0        10        11
1        12        13
2        14        15
  • $\begingroup$ Hey, thanks for commenting. Please run your code with the same input but with chunk_size=4. Why some columns are Float and others Int? $\endgroup$ – joann2555 Jun 18 '20 at 21:26
  • $\begingroup$ If you ran it on the same input with 6 values it will not be able to split it into 4 columns while populating all the cells. You need len(input_series) % chunk_size = 0 in order to populate all values. The columns are float64 because the last two column will contain NaNs because it doesn't have enough values in the series to fill the whole matrix. $\endgroup$ – Samarth Jun 18 '20 at 21:36
  • $\begingroup$ Got it. Since i will be working mostly with float values, this won't be a problem. Thanks! $\endgroup$ – joann2555 Jun 18 '20 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.