3

I have a dictionary of lists (equal length), which I would like to convert to a dataframe such that each key in the dictionary represents one column (or series) in the dataframe, and the list of values corresponding to each key are converted into individual records in the column.

Suppose the contents of dictionary are:

sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}

I would like the contents of dataframe to be:

    col1        col2
    ---         ---
0   abc         1a2b
1   def pqr     lmno
2   w xyz       qr st

I have tried solving this by first converting the dictionary to a dataframe, and then taking the transpose of the dataframe.

import pandas as pd

sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}
sample_df = pd.DataFrame(list(sample_dict.items()))
sample_df.transpose()

This gives the following output:

     0                       1
    ---                     ---
0   col2                    col1
1   [1a2b, lmno, qr st]     [abc, def pqr, w xyz]

I am not sure how to proceed further.

SaadH
  • 1,158
  • 2
  • 23
  • 38

1 Answers1

2

Simply:

import pandas as pd
sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}
sample_df = pd.DataFrame(sample_dict)
print (sample_df)

Output:

      col1   col2
0      abc   1a2b
1  def pqr   lmno
2    w xyz  qr st
Joe
  • 12,057
  • 5
  • 39
  • 55