If the usage of pandas is possible, you can achive a flexible solutiion with the following:
Definition of the data:
df=pd.DataFrame({'Loc': {0: 'A', 1: 'A', 2: 'B ', 3: 'C', 4: 'B'},
'ID': {0: 'ABC1', 1: 'DFT1', 2: 'HJH5', 3: 'HKL', 4: 'GTY'},
'filter': {0: 'GHY', 1: 'FGH', 2: 'GHY', 3: 'BHY', 4: 'FGH'},
'P1': {0: 55.6, 1: 67.8, 2: 67.0, 3: 78.0, 4: 60.0}})
Creation of the repetive columns:
cols=["{}_{}".format(N, c) for N in range(0,df.groupby('filter').count()['ID'].max()) for c in df.columns]
Here, I first find the maximum required repitions by looking for the max occurences of each filter df.groupby('filter').count()['ID'].max()
. The remaining code is just formating by adding a leading number.
Creation of new dataframe with filter
as index and the generated columns cols
as columns
df_new=pd.DataFrame(index=set(df['filter']), columns=cols)
Now we have to fill in the data:
for fil in df_new.index:
values=[val for row in df[df['filter']==fil].values for val in row]
df_new.loc[fil,df_new.columns[:len(values)]]=values
Here two things are done: First, the selected values based on the filter name fil
are flattend by [val for row in df[df['filter']==fil].values for val in row]
. Then, these values are filled into the dataframe starting at the left.
The result is as expected:
0_Loc 0_ID 0_filter 0_P1 1_Loc 1_ID 1_filter 1_P1
GHY A ABC1 GHY 55.6 B HJH5 GHY 67.0
BHY C HKL BHY 78.0 NaN NaN NaN NaN
FGH A DFT1 FGH 67.8 B GTY FGH 60.0