1

I would like to create a dataframe from 2 python lists that I have.

Say I have the following 2 lists;

x = [1,2,3]
z = ['a','v','d']

I have initialized a dataframe

data = pd.DataFrame(columns = ['Type', 'Data']

and this is one of the things that I have tried doing.

df = data.append({'Type': x, 'Data' : z}, ignore_index = True)

but it results in the following dataframe

   Type       Data
0 [1, 2, 3]  [a, v, d]

However, this is what I actually want it to look like

   Type    Data
0  1      a
1  2      v
2  3      d

How would I do this? Thank you in advance.

Susan-l3p
  • 157
  • 1
  • 13
  • 1
    `pd.DataFrame({'Type': x, 'Data' : z})`? – Chris Sep 12 '19 at 10:46
  • Possible duplicate of [Convert Python dict into a dataframe](https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe) – Chris Sep 12 '19 at 10:46

3 Answers3

2

Try this :

df =  pd.DataFrame(zip(x,z),columns=['Type', 'Data'])
print(df)

Output :

   Type Data
0     1    a
1     2    v
2     3    d
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

Convert dictionary to DataFrame:

data = pd.DataFrame(columns = ['Type', 'Data'])
df = data.append(pd.DataFrame({'Type': x, 'Data' : z}), ignore_index = True)
print (df)
  Type Data
0    1    a
1    2    v
2    3    d
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thank you this is what I wanted. But now I'm just not sure how I would append to this dataframe. Say I want to add r = [5,6,7] to Type and w = [r,t,w] to Data in the same way. How would I do this? – Susan-l3p Sep 14 '19 at 20:01
  • @Susan-l3p - You can again call `df = data.append(pd.DataFrame({'Type': x, 'Data' : z}), ignore_index = True)` – jezrael Sep 15 '19 at 05:09
0

You can use assign:

data.assign(Type=x, Data=z)

  Type  Data
0   1   a
1   2   v
2   3   d
Allen Qin
  • 19,507
  • 8
  • 51
  • 67