Aly
Aly

Reputation: 367

How to concatenate two lists into pandas DataFrame?

Hey I have two different lists:

  1. One is list of the strings:
    ['A',
     'B',
     'C',
     'D',
     'E']
  1. Second list contains floats:
     [(-0.07154222477384509, 0.03681057318023705),
     (-0.23678194754416643, 3.408617573881597e-12),
     (-0.24277881018771763, 6.991906304566735e-13),
     (-0.16858465905189185, 7.569580517034595e-07),
     (-0.21850787663602167, 1.1718560531238815e-10)]

I want have one DataFrame with three columns that look like this:

var_name      val1                val2 
A         -0.07154222477384509     0.03681057318023705

Best if the new DataFrame dont have scientific notation so I dont want them as strings.

Upvotes: 3

Views: 3734

Answers (1)

jezrael
jezrael

Reputation: 862611

Use list copmprehension with zip for list of tuples and pass toDataFrame constructor:

a = ['A',
     'B',
     'C',
     'D',
     'E']
b = [(-0.07154222477384509, 0.03681057318023705),
     (-0.23678194754416643, 3.408617573881597e-12),
     (-0.24277881018771763, 6.991906304566735e-13),
     (-0.16858465905189185, 7.569580517034595e-07),
     (-0.21850787663602167, 1.1718560531238815e-10)]

df = pd.DataFrame([(a, *b) for a, b in zip(a,b)])
print (df)
   0         1             2
0  A -0.071542  3.681057e-02
1  B -0.236782  3.408618e-12
2  C -0.242779  6.991906e-13
3  D -0.168585  7.569581e-07
4  E -0.218508  1.171856e-10

With set columns names:

df = pd.DataFrame([(a, *b) for a, b in zip(a,b)],
                  columns=['var_name','val1','val2'])
print (df)
  var_name      val1          val2
0        A -0.071542  3.681057e-02
1        B -0.236782  3.408618e-12
2        C -0.242779  6.991906e-13
3        D -0.168585  7.569581e-07
4        E -0.218508  1.171856e-10

Upvotes: 5

Related Questions