user3447653
user3447653

Reputation: 4158

Append values to pandas dataframe

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 !!

Upvotes: 1

Views: 2953

Answers (1)

Aleksey Bilogur
Aleksey Bilogur

Reputation: 3856

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})

Upvotes: 1

Related Questions