Akshit Gupta
Akshit Gupta

Reputation: 17

Creating a DataFrame in Pandas for a two columns and single data row

I am new to Pandas and DataFrame concept and learning through experiments. While creating a new DataFrame I tried with the following code, but gives me some error. Please suggest.

import pandas as pd

akshit = pd.DataFrame({'Name': 'Akshit', 'Last': 'Gupta'})

I expected the dataframe to be created, but I am getting the following error:

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

Upvotes: 1

Views: 38

Answers (3)

Neel
Neel

Reputation: 370

As the error message mentions, since your dict values are scalers, the index can't be auto-inferred and must be mentioned explicitely. SO this will work

akshit = pd.DataFrame({'Name': 'Akshit', 'Last': 'Gupta'}, index = [0])

Obviously, you can extend it to multiple rows

names = pd.DataFrame([{'Name': 'Akshit', 'Last': 'Gupta'},
                      {'Name': 'Neel', 'Last': 'Ray'} , index = [0,1])

Alternately, You can mention the values of your dict as lists, so that the index can be inferred by the position of elements in the lists.

alshit = pd.DataFrame([{'Name': ['Akshit'], 'Last': ['Gupta']})

Upvotes: 0

Franco Piccolo
Franco Piccolo

Reputation: 7410

As the suggestion says, you can pass an index like:

akshit = pd.DataFrame({'Name': 'Akshit', 'Last': 'Gupta'}, index=[0])

Upvotes: 2

DSGym
DSGym

Reputation: 2867

Name is the column name and should get an array of data. This is why you have to use brackets for the columns:

akshit = pd.DataFrame({'Name': ['Akshit'], 'Last': ['Gupta']})
akshit

Out[7]: 
     Name   Last
0  Akshit  Gupta

Upvotes: 2

Related Questions