2

The purpose of this script is to produce a data frame that is generated through code written in object oriented style.

The problem is the outcome of this script is an empty data frame.

There is no error.

Here is the code:

import pandas as pd


class Dataframe:
    def __init__(self):
        self.df = pd.DataFrame()

    def name(self):
        self.df['name'] = ["Hamza", "Carmen"]
        return print(self.df['name'])

    def age(self):
        self.df['age'] = [20, 15]
        return self.df['age']

    def sex(self):
        self.df['sex'] = ["Male", "Female"]
        return self.df['sex']

    def address(self):
        self.df['adress'] = ["Miami", "Seattle"]
        return self.df['adress']

    def print(self):
        return print(self.df)


x = Dataframe()
x.print()
1
  • at no point are you calling the methods that are populating the df. so it correctly is returning an empty df Commented May 28, 2020 at 11:42

4 Answers 4

3

You need to call the methods you have created to populate the DataFrame.

import pandas as pd


class Dataframe:
    def __init__(self):
        self.df = pd.DataFrame()
        self.name()
        self.age()
        self.sex()
        self.address()

    def name(self):
        self.df['name'] = ["Hamza", "Carmen"]
        return print(self.df['name'])

    def age(self):
        self.df['age'] = [20, 15]
        return self.df['age']

    def sex(self):
        self.df['sex'] = ["Male", "Female"]
        return self.df['sex']

    def address(self):
        self.df['adress'] = ["Miami", "Seattle"]
        return self.df['adress']

    def print(self):
        print(self.df)


x = Dataframe()
x.print()
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry @SayedGouda, there was an error in the original code, that I copied. Erfan fixed it.
2

You must call the methods of the class

x = Dataframe()
x.name()
x.age()
...

1 Comment

On the line switch self.df['name'] = ["Male", "Female"] 'name' -> 'sex'
1

You didn't call DataFrame().name/age or any other functions you defined within the class. That's why it's returning the default self.df value which is empty

Comments

0

One small thing added to the answers above:

print() function return None. So return print(xx) will yield value as None, not the one you expected.

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.