Reputation: 479
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
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)
Option-2
thisdict = {}
thisdict["Column1"] = [1]
thisdict["Column2"] = [2]
print(thisdict)
print("Below is Option2:")
df = pd.DataFrame(thisdict)
display(df)
Upvotes: 1
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
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
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