1

I have this constant value and list of lists in my result. I need to add the constant and its corresponding list of list to a row in pandas dataframe. Dataframe would have 2 columns - Col1 and Col2. I generate these values inside a for loop.

Code used to generate the values:

      for key, elem in dict.items():
        print key
        length = len(elem)
        elements = list(elem)
        values = []
        firsthalf = elements[:len(elemlist)/2]
        print firsthalf

Values generated:

[[0.040456528559673702, -0.085805111083485666]]
11
-----
[[0.035220881869308676, -0.063623927372217309, 0.0063355856789509323]]
12

Dataframe:

        Col1                                                                    Col2
        [[0.040456528559673702, -0.085805111083485666]]                         11
        [[0.035220881869308676, -0.063623927372217309, 0.0063355856789509323]]  12

Any help would be appreciated. Thanks !!

user3447653
  • 3,968
  • 12
  • 58
  • 100
  • Possible duplicate: http://stackoverflow.com/questions/41888080/python-efficient-way-to-add-rows-to-dataframe/41888241#41888241 – sundance Jan 27 '17 at 18:22

1 Answers1

1

It's easiest to append your objects to lists, then use those to initialize:

import pandas as pd
col1 = []
col2 = []
for key, elem in dict.items():
     length = len(elem)
     elements = list(elem)
     values = []
     firsthalf = elements[:len(elemlist)/2]  # elemlist?
     col1.append(key)
     col2.append(firsthalf)

df = pd.DataFrame({'col1': col1, 'col2': col2})
Aleksey Bilogur
  • 3,686
  • 3
  • 30
  • 57