1

I am trying to convert a list into dataframe using python. I have all the necessary data in my list(correct data), in the form of list of dictonaries. See list of dictonaries below:

 [{'ABC': 'abc1', 'DEF': 'def1', 'GHI': 'ghi1', 'JKL': 'jkl1', 'MNO': 'mno1', 'PQR': 'pqr1', 'STU': 'stu1', 'VWX': 'vwx1', 'YZ': 'yz1'},
 {'ABC': 'abc2', 'DEF': 'def2', 'GHI': 'ghi2', 'JKL': 'jkl2', 'MNO': 'mno2', 'PQR': 'pqr2', 'STU': 'stu2', 'VWX': 'vwx2', 'YZ': 'yz2'},......

I am using the following command to convert it to a dataframe.

newdf = pd.DataFrame.from_dict(case_list_new)

Instead of taking the dictionary keys as column headers, the dataframe is taking the numbers 0-8 as column headers, and printing the column names in a loop where the dictionary values should be. This is the dataframe output I get :

     0   1    2   3   4   5   6   7   8  
0   ABC DEF  GHI JKL MNO PQR STU VWX YZ
1   ABC DEF  GHI JKL MNO PQR STU VWX YZ

What could be the reason for this output and how may I put it right ? Any help would be hugely appreciated.

7
  • This should have worked. Trying pd.DataFrame.from_dict(data, orient='columns') works for me? Commented Jun 18, 2018 at 7:06
  • Hi @coldspeed, tried that, still the same output :( Commented Jun 18, 2018 at 7:09
  • 1
    Then your actual data has something that you have not shown here. Please provide a minimal reproducible example and make sure the data reproduces your problem. Commented Jun 18, 2018 at 7:09
  • @learner, can you try just use DataFrame constructor ? Commented Jun 18, 2018 at 7:10
  • That worked for me and Mr.@Nihal. Please share your source code. Commented Jun 18, 2018 at 7:22

1 Answer 1

0
df = [{'ABC': 'abc1', 'DEF': 'def1', 'GHI': 'ghi1', 'JKL': 'jkl1', 'MNO': 'mno1', 'PQR': 'pqr1', 'STU': 'stu1',
   'VWX': 'vwx1', 'YZ': 'yz1'},
  {'ABC': 'abc2', 'DEF': 'def2', 'GHI': 'ghi2', 'JKL': 'jkl2', 'MNO': 'mno2', 'PQR': 'pqr2', 'STU': 'stu2',
   'VWX': 'vwx2', 'YZ': 'yz2'}]

newdf1 = pd.DataFrame(df)
newdf2 = pd.DataFrame.from_dict(df)
print(newdf1)
print(newdf2)

output:

    ABC   DEF   GHI   JKL   MNO   PQR   STU   VWX   YZ
0  abc1  def1  ghi1  jkl1  mno1  pqr1  stu1  vwx1  yz1
1  abc2  def2  ghi2  jkl2  mno2  pqr2  stu2  vwx2  yz2

    ABC   DEF   GHI   JKL   MNO   PQR   STU   VWX   YZ
0  abc1  def1  ghi1  jkl1  mno1  pqr1  stu1  vwx1  yz1
1  abc2  def2  ghi2  jkl2  mno2  pqr2  stu2  vwx2  yz2
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.