Home > Software design >  Dataframe Operation Splicing
Dataframe Operation Splicing

Time:05-14

I have a single column dataframe without headers and I want to split it into multiple columns as follows The current dataframe -

1
2
3
4
5
.
.
100

I want to represent it as -

1 6 .. ..  96
2 7 .. ..  97
3 8 .. ..  98
4 9 .. ..  99
5 10 .. .. 100

CodePudding user response:

Assuming such a DataFrame:

df = pd.DataFrame({'col': range(1, 101)})

you can use the underlying numpy array to reshape:

df2 = pd.DataFrame(df['col'].to_numpy().reshape(5, -1, order='F'))

output:

   0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  \
0   1   6  11  16  21  26  31  36  41  46  51  56  61  66  71  76  81  86  91   
1   2   7  12  17  22  27  32  37  42  47  52  57  62  67  72  77  82  87  92   
2   3   8  13  18  23  28  33  38  43  48  53  58  63  68  73  78  83  88  93   
3   4   9  14  19  24  29  34  39  44  49  54  59  64  69  74  79  84  89  94   
4   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95   

    19  
0   96  
1   97  
2   98  
3   99  
4  100
  • Related