user13456401
user13456401

Reputation: 479

How to convert a python list to pandas Dataframe in python

I have this python list and I need to convert it into pandas dataframe.

This is how my list looks like:

thisdict = {}

thisdict["Column1"] = 1
thisdict["Column2"] = 2

thisdict # this print

{'Column1': 1, 'Column2': 2}

And I need to convert this to pandas dataframe.

I tried:

df = pd.DataFrame(thisdict)

and I got the error as below:

ValueError: If using all scalar values, you must pass an index

Can someone please help me?

Upvotes: 1

Views: 151

Answers (4)

a11
a11

Reputation: 3396

It's not clear from your question what you want, but here are a couple options; I think you probably want the second option. To achieve it, make sure you use a list when you build your dictionary.

Option-1

thisdict = {}
thisdict["Column1"] = 1
thisdict["Column2"] = 2
print(thisdict)

print("Below is Option1:")
df = pd.DataFrame(list(thisdict.items()),columns = ['ColumnA','ColumnB'])
display(df)

enter image description here

Option-2

thisdict = {}
thisdict["Column1"] = [1]
thisdict["Column2"] = [2]
print(thisdict)

print("Below is Option2:")
df = pd.DataFrame(thisdict)
display(df)

enter image description here

Upvotes: 1

Scott Boston
Scott Boston

Reputation: 153460

If your dictionary is going to one row of a dataframe you need to pass in a list with a single element.

pd.DataFrame(thisdict, index=[0])

Output:

   Column1  Column2
0        1        2

Upvotes: 1

Suraj
Suraj

Reputation: 2477

You are supposed to assign the column as lists in your code.

Try replacing lines 2 and 3 with :

thisdict["Column1"] = [1]
thisdict["Column2"] = [2]

Complete code :

thisdict = {}
thisdict["Column1"] = [1]
thisdict["Column2"] = [2]
df = pd.DataFrame(thisdict)

Output :

    Column1 Column2
0         1       2

Upvotes: 1

rhug123
rhug123

Reputation: 8768

If for some reason you didn't want to make your columns as lists, you could do this.

df = pd.DataFrame(pd.Series(thisdict)).transpose()

Upvotes: 1

Related Questions