1

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

3 Answers 3

2

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

Comments

2

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

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

Comments

0

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']})

Comments

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.