Trying to convert consecutive columns to rows in pandas. Ex: Consecutive column names are sequential numbers along with some strings i.e Key1,Val1,...., KeyN,ValN in DataFrame. You can use below code to generate the dataframe.
df = pd.DataFrame({'City': ['Houston', 'Austin', 'Hoover'],'State': ['Texas', 'Texas', 'Alabama'],'Name':['Aria', 'Penelope', 'Niko'],'Key1':["test1", "test2", "test3"],'Val1':[28, 4, 7],'Key2':["test4", "test5", "test6"],
'Val2':[82, 45, 76],'Key3':["test7", "test8", "test9"],'Val3':[4, 76, 9],'Key4':["test10", "test11", "test12"],'Val4':[97, 66, 10],'Key5':["test13", "test14", "test15"],'Val5':[4, 10, '']},columns=['City', 'State', 'Name', 'Key1', 'Val1', 'Key2', 'Val2', 'Key3', 'Val3', 'Key4', 'Val4', 'Key5', 'Val5'])
I tried melt function as below:
df.melt(id_vars=['City', 'State'], var_name='Column', value_name='Key')
But I got the below output:
The problem is for every key, val column has different rows. The expected output is below:


