Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a Dataframe in Python?

I am doing some work in a jupyter notebook using python and pandas and am getting a weird error message and would really appreciate the help. The error I am receiving is "NameError: name 'DataFrame' is not defined"

import pandas as pd 

d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
     'age': [22,38,26,35],
     'fare': [7.25, 71.83, 0 , 8.05], 
     'survived?': [False, True, True, False]}

df = DataFrame(d)

print(df)
like image 646
Chase Kregor Avatar asked Nov 03 '16 04:11

Chase Kregor


People also ask

How do you define a data frame?

What is a DataFrame? A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns.

What Is syntax of DataFrame in Python?

DataFrame(data, index=['first', 'second'], columns=['a', 'b']) #With two column indices with one index with other name df2 = pd. DataFrame(data, index=['first', 'second'], columns=['a', 'b1']) print df1 print df2. Its output is as follows − #df1 output a b first 1 2 second 5 10 #df2 output a b1 first 1 NaN second 5 ...

How do you define an empty DataFrame in Python?

You can create an empty dataframe by importing pandas from the python library. Later, using the pd. DataFrame(), create an empty dataframe without rows and columns as shown in the below example.


1 Answers

The below code works:

import pandas as pd 

d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
     'age': [22,38,26,35],
     'fare': [7.25, 71.83, 0 , 8.05], 
     'survived?': [False, True, True, False]}

df = pd.DataFrame(d)

print(df)

Instead of:

DataFrame(d)

You have to do:

pd.DataFrame(d)

Because you've imported pandas as 'pd'.

You can achieve the same end much better by:

df = pd.DataFrame({'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
                   'age': [22,38,26,35],
                   'fare': [7.25, 71.83, 0 , 8.05], 
                   'survived': [False, True, True, False]})

I removed the '?' from the 'survived' feature as it's not a good idea to have special characters in your feature names.

like image 58
mikkokotila Avatar answered Oct 22 '22 20:10

mikkokotila