2017-07-11 74 views
2

我創建了一個類對象,它從數據庫中檢索信息並將其存儲在pandas中,以便我可以使用某些數據科學庫進行操作。返回與dtype一起使用np.divide函數時的數字:float64

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() 

這將返回:

2 6558.4 
Name: interest, dtype: float64 

我只需要它返回整數6558.4,因爲這是顯示在Django模板。

我已經試過這樣:

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

但我得到一個KeyError: 'interest'

回答

0

您所描述的結果是單個值的熊貓系列。
爲了得到它包含浮點值,你應該使用:

self.div_intmnthgoal_workingdays.iloc[0] 
+0

阿德里安馬蒂斯,謝謝!隨着我學習的進步,我需要進一步理解.iloc。你的建議已經明確指出了我的正確方向。 –

+0

'iloc'用於基於整數位置的索引(從0到長度-1)。請參閱https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html?highlight=iloc#pandas.Series.iloc –

+0

再次感謝!我記得在我參加的數據科學課程中簡要回顧了這一點。我相信我的問題的一部分是迄今爲止所有的理論。這是看到它以這種方式使用的進展,所以我很感謝你和其他人的幫助! –

0

您可以通過使用.values屬性或方法.tolist得到的值(無指標)。

例如,如果我有此Series

>>> s 
2 3 
dtype: int64 

那麼值是:

>>> s.values 
array([3], dtype=int64) 
>>> s.tolist() 
[3] 

這可以被索引像任何其他序列樣類:

>>> s.values[0] 
3 
>>> s.tolist()[0] 
3 
相關問題