Of course, we can come up with a solution where we will use 'c4'
, but I see the solution this way.
We can bring to the form you need with the help of an auxiliary column 'group'
. It will help us to index the values for future transformation.
Now we will write a function that will create a pd.Series
. We take the values and place them into one array using flatten()
.
def grouping(g):
return pd.Series(g[['c1', 'c2', 'c3']].values.flatten(),
index=[f'c{i+1}' for i in range(9)])
We apply the function to the grouped DataFrame
by the auxiliary column 'group'
.
Full code:
import pandas as pd
data = {
'c1': [1, 10, 100, 1, 10, 100],
'c2': [2, 20, 200, 2, 20, 200],
'c3': [3, 30, 300, 3, 30, 300],
'c4': [0, 1, 2, 0, 1, 2]
}
df = pd.DataFrame(data)
df['group'] = df.index // 3
def grouping(g):
return pd.Series(g[['c1', 'c2', 'c3']].values.flatten(),
index=[f'c{i+1}' for i in range(9)])
transformed_df = df.groupby('group').apply(grouping).reset_index(drop=True)