-1

I'm trying to convert a df that has the data divided every 3 columns into just three. An example is from this:

C1 C2 C3 C4 C5 C6  C7  C8  C9 
1  6   9  A  D  G  1A  6A  9A
2  7  10  B  E  H  2A  7A  10A
3  8  11  C  F  I  3A  8A  11A

To this:

C1 C2 C3
1  6   9
2  7  10
3  8  11
C4 C5 C6
A  D  G
B  E  H
C  F  I
C7 C8 C9
1A 6A 9A
2A 7A 10A
3A 8A 11A
7
  • Are those 3 different DataFrames at the end there? Or just 1?
    – NYC Coder
    Oct 29, 2020 at 21:12
  • It might help to explain a bit why you'd want to do so. This seems like something you would rarely want to do.
    – Metropolis
    Oct 29, 2020 at 21:25
  • 1
    @Metropolis: this is called pivoting (in this case, from wide-form to long-form). Except we generally don't want to pivot the column names C1 C1 C1, C2 C2 C2, C3 C3 C3 into actual rows of strings, mixed in with the data; we put them in a separate new column called e.g. variable.
    – smci
    Oct 29, 2020 at 21:46
  • 1
    @smci I agree that is a strange transformation but you can't use pivoting here. Oct 29, 2020 at 22:02
  • 1
    @MykolaZotko: melt, unstack and pivot, in some order. But first the OP must make this illegal example legal. Seems like the header and data rows could only ever have been read in as huge long string, not 3x3 individual columns. This question is not a reusable resource on SO, as such.
    – smci
    Oct 29, 2020 at 22:15

1 Answer 1

1

You can use numpy:

arr = np.hsplit(np.vstack([df.columns.values, df.values]), 3)
pd.DataFrame(np.vstack(arr))

Output:

     0   1    2
0   C1  C2   C3
1    1   6    9
2    2   7   10
3    3   8   11
4   C4  C5   C6
5    A   D    G
6    B   E    H
7    C   F    I
8   C7  C8   C9
9   1A  6A   9A
10  2A  7A  10A
11  3A  8A  11A

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