Search code examples
pythonpandasindexingframe

Converting data in the dictionary into a dataframe with index in the rows


I have the following problem. Given the dictionary dict = { 'value_1': [12,25,30,45,60] , 'value_2': [ 15,21,31]} What is an easier way to convert the above dictionary into a data frame with one column being the concatenation of items of the two keys and the other column being the index to each of these items? Following should be the output index 0 1 0 value_11 12 1 value_12 25 2 value_13 30 3 value_14 45 4 value_15 60 0 value_21 15 1 value_22 21 2 value_23 31

The approach I took was quite time consuming. I first took the items and made a list of that. For the indexes I ran a for loop for i , indexing will be 'value_1'+str(i)and then combined everything into a dataframe. Is there any easier way to do this?


Solution

  • Probably not the fastest, but you can try:

    pd.concat(pd.DataFrame([[f'{k}{i+1}', val] for i,val in enumerate(v)]) 
              for k,v in d.items() )
    

    output:

              0   1
    0  value_11  12
    1  value_12  25
    2  value_13  30
    3  value_14  45
    4  value_15  60
    0  value_21  15
    1  value_22  21
    2  value_23  31