How to create a dataframe from a list (or multiple lists) with pandas ?

Published: March 24, 2021

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

Examples of how to create a dataframe from a list (or multiple lists) with pandas

Create a list of random integers in python

Let's first create a list of random integers:

import pandas as pd
import random

l = [random.randint(1,10) for i in range(10)]

returns for example

[5, 4, 9, 9, 8, 10, 9, 5, 5, 4]

Create a dataframe from a list with pandas

To create a dataframe from this list, a solution is to do:

df = pd.DataFrame(data=l,columns=['A'])

    A
0   5
1   4
2   9
3   9
4   8
5  10
6   9
7   5
8   5
9   4

Another solution

data = np.array(l)
data = data.reshape(1,data.shape[0])

df = pd.DataFrame(data=data,columns=['C{}'.format(i) for i in range(10)])

returns

   C0  C1  C2  C3  C4  C5  C6  C7  C8  C9
0   5   4   9   9   8  10   9   5   5   4

Create a dataframe from multiple lists with pandas

Example of how to create a dataframe from multiple lists

l1 = [random.randint(1,10) for i in range(10)]
l2 = [random.randint(1,10) for i in range(10)]
l3 = [random.randint(1,10) for i in range(10)]

data = {'A':l1,'B':l2,'C':l3}

df = pd.DataFrame(data)

returns

    A  B   C
0   9  8   9
1   8  9   5
2   2  9   8
3   6  7  10
4   3  2   8
5  10  3  10
6   9  4   1
7   1  9   3
8   7  9   3
9   2  3   1

References