Atila
Atila

Reputation: 51

Return values from nested lists into PandasDataFrame

I have a list containing 2 lists that looks as the follows:

[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

What I need to have at the end of the day, is to have 2 columns in a PandasDataFrame, the first column should hold the values found in the first list, and the second column should hold the values in the second list.

I want to iterate over each of these lists and return every single value in it into a separate column in PandasDataFrame. Where col0 in PandasDataFrame should hold the values in the first list, and the col1 in PandasDataFrame should hold values in the second list.

I am expecting output like this:

enter image description here

Is there a compact way to do so?

Thanks.

Upvotes: 1

Views: 106

Answers (3)

Terry
Terry

Reputation: 2811

one way to do this is using transpose:

df = pd.DataFrame(yourList).T

If you want to change the columns names you can add

df = df.add_prefix('col')

Upvotes: 0

Sahaj Adlakha
Sahaj Adlakha

Reputation: 156

A simple way to do this is by converting the list into a dictionary and then creating a Data Frame from that dictionary as explained below:

l =[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

# Creating a dictionary using dictionary comprehension
d = {'col'+str(i) : l[i] for i in range(len(l))}

df = pd.DataFrame(d)

output

Upvotes: 1

BossaNova
BossaNova

Reputation: 1527

As your lists are arranged rather for rows than columns, I would first build the data frame as is and then transpose it:

data = [[0, 0, 0, 0,], [1, 1, 1, 1,]]
columns = ['a', 'b', 'c', 'd']
df = pd.DataFrame(data, columns=columns)
df = df.transpose()

Upvotes: 0

Related Questions