1

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?

3
  • 1
    How do you want your dataframe? One row two columns or two rows one column? Commented Jul 9, 2020 at 20:12
  • Assign 1 and 2 as lists thisdict["Column1"] = [1] and thisdict["Column2"] = [2] Commented Jul 9, 2020 at 20:13
  • @ScottBoston I need two columns and one row Commented Jul 9, 2020 at 20:20

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know how can set columns to that data frame as well? So the column names are Column1 and Column2
The column names are what you are asking for.
1

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()

Comments

1

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

Comments

1

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

1 Comment

This is quite helpful. I needed the second option. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.