Search code examples
pythondjangopandasnumpydivide

Return just the number when using the np.divide function with dtype:float64


I have created a class object that retrieves information from a database and stores it in pandas so I can use some data science library's for manipulation.

class IntDailyGoals (object):
    def __init__(self, begin_date, end_date, store=None):
        self.begin_date = begin_date
        self.end_date = end_date
        self.store = store
        self.int_mnth_goal = pd.DataFrame(list(StoreGoalsInput.objects.values('store_number',
                                                                              'interest',
                                                                              'date')))
        self.int_mnth_goal['interest'] = pd.to_numeric(self.int_mnth_goal['interest'])
        self.int_mnth_goal['date'] = pd.to_datetime(self.int_mnth_goal['date'])
        self.mnth_goal_int =self.int_mnth_goal[(self.int_mnth_goal['date'] >= self.begin_date) &
                                               (self.int_mnth_goal['date'] <= self.end_date) &
                                               (self.int_mnth_goal['store_number'] == self.store.store_number)]
        self.mnth_goal_int= self.mnth_goal_int['interest']
        self.tot_workingdays = np.busday_count(np.datetime64(self.begin_date),
                                               np.datetime64(self.end_date),
                                               weekmask='Mon Tue Wed Thu Fri Sat')
        self.div_intmnthgoal_workingdays = round(np.divide(self.mnth_goal_int, self.tot_workingdays),2)


    def get_div_goalsint_wdays(self):
        div_goalsint_wdays = self.div_intmnthgoal_workingdays
        return div_goalsint_wdays

    def __str__(self):
        return self.get_div_goalsint_wdays()

This returns:

2    6558.4 
Name: interest, dtype: float64

I just need it to return the integer 6558.4 as this is being displayed in a Django template.

I have tried this:

    def get_div_goalsint_wdays(self):
    div_goalsint_wdays = self.div_intmnthgoal_workingdays['interest']
    return div_goalsint_wdays

but I get a KeyError: 'interest'


Solution

  • The result you describe is a pandas Series with a single value.
    To get the float value it contains, you should use:

    self.div_intmnthgoal_workingdays.iloc[0]