I am having the Source data frame like below ;
Source Dataframe
I would like to create a resultant data frame as follows ;
Resultant Dataframe
I am having the Source data frame like below ;
Source Dataframe
I would like to create a resultant data frame as follows ;
Resultant Dataframe
Set Parameter as index, then call .apply on value and create range from 1 to n+1, then explode and finally reset the index
df.set_index('Parameter')['value'].apply(lambda x: range(1, x+1)).explode().reset_index()
Parameter value
0 Apple 1
1 Orange 1
2 Orange 2
3 Mango 1
4 Mango 2
5 Mango 3
6 Mango 4
7 Mango 5
You can even avoid setting/resetting index, by assigning column then exploding it:
>>> df.assign(value=df['value'].apply(lambda x: range(1, x+1))).explode('value')
Parameter value
0 Apple 1
1 Orange 1
1 Orange 2
2 Mango 1
2 Mango 2
2 Mango 3
2 Mango 4
2 Mango 5
You could do this:
new_params = []
new_values = []
for param, value in zip(source_df.parameter, source_df.value):
new_params.append([param]*value)
new_values.append(list(range(1,value+1)))
resultant_df = pd.DataFrame({'parameter':new_params, 'value':new_values})
I cannot think of a simpler way using pandas.