0

I am trying to use class and objects in Python. I want to use process a Dataframe through a class and then make some changes such as changing the datetime time format and removing bad columns. My question is that while doing such modification, I needed to create a variable named req_cols. Should I also use self.req_cols while using classes and objects. I won't be using such variable through any of the instance method for sure. When to use self and when not ?

import pandas as pd
class MyClass:

    def __init__(self, my_dataframe):
        self.dataframe = my_dataframe
    def modification(self):
        self.dataframe['Date_time'] = self.dataframe['Date'] + ' ' + self.dataframe['Time']
        self.dataframe['Date_time'] = pd.to_datetime(self.dataframe['Date_time'],format='%Y-%m-%d %H:%M:%S')
        req_cols = [x for x in self.dataframe.columns if 'Unnamed' not in x]
        self.dataframe = self.dataframe[req_cols]
        return self.dataframe

bn_futures = pd.read_csv('C:\\IData\\RELIANCE-I.txt')
a = MyClass(bn_futures)
# b = MyClass(my_dataframe)
ashish gupta
  • 43
  • 1
  • 5
  • There is not any particular magic here. Python is noticeably *less* magical and *more* consistent than most languages here. You use `self.` when `self` is the thing that contains the value you want. Just like how you write `pd.read_csv` because `pd` is the thing that contains `read_csv`. You don't put anything in front of `req_cols` because `req_cols` is already the thing you want, because you just finished creating it and calling it that. – Karl Knechtel Jan 22 '22 at 13:48
  • You might also try reading through [the official Python tutorial on classes](https://docs.python.org/3/tutorial/classes.html), especially around [this point](https://docs.python.org/3/tutorial/classes.html#method-objects). – Karl Knechtel Jan 22 '22 at 13:52
  • @KarlKnechtel I think you misunderstood what the question asks. – user3840170 Jan 22 '22 at 13:53
  • "When to use self and when not ?" seems pretty straightforward to me. If the question is "should I assign this value as an attribute even though it works fine as is and I'm not going to use it in other methods?" then the answer is "no, obviously not", and doesn't merit explanation. The interpretation that makes sense as an actual question is "when is `self.` required in order to access the value?". – Karl Knechtel Jan 22 '22 at 13:54

0 Answers0