[英]Mean normalization different versions of code
我想說的是規范化我的數據框架,當我實現代碼的第一個版本時,我會獲得規范化的值,但是當我實現版本2的時候,我會得到一個錯誤,稱為stop iteration
。 ["1B","2B","3B","HR","BB"]
是我的數據框中的列。
版本1:
def meanNormalizeRates(df):
subRates = df[["1B","2B","3B","HR","BB"]]
df[["1B","2B","3B","HR","BB"]] = subRates - subRates.mean(axis=0)
return df
stats = stats.groupby('yearID').apply(meanNormalizeRates)
stats.head()
版本2:
def mean(df):
for val in ["1B","2B","3B","HR","BB"]:
stats[val] = stats[val] -stats[val].mean(axis=0)
stats = stats.groupby('yearID').apply(mean)
stats.head()
我無法理解兩個版本之間的區別。
一個很好的例子
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9],
'gate' : [9, 7, 4,6, 9]}
frame = pd.DataFrame(data)
frame.head()
版本1.1
def std(df):
temp = df[['gate', 'pop']]
df[['gate', 'pop']] = temp - temp.mean(axis=0)
return df
frame.groupby('year').apply(std)
gate pop state year
0 9 1.5 Ohio 2000
1 7 1.7 Ohio 2001
2 4 3.6 Ohio 2002
3 6 2.4 Nevada 2001
4 9 2.9 Nevada 2002
版本1.2
def mean(df):
for val in ['gate', 'pop']:
df[val] = df[val]- df[val].mean(axis=0)
frame.groupby('year').apply(mean)
error: stop iteration
好的,所以因為在mean()
函數中沒有return語句(在示例1.2中),所以該函數只為每個組返回None
。 您得到的StopIteration
錯誤不是很清楚,但是正在發生的是:
apply()
在每個組上調用mean()
函數。 None
。 None
的列表 apply()
嘗試在列表中查找非None
值,這將引發StopIteration
異常。 因此,基本上,您可以通過執行以下操作來重現錯誤:
eg_list = [None, None, None]
v = next(v for v in eg_list if v is not None)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-12-93b31b7a51e4> in <module>()
----> 1 v = next(v for v in eg_list if v is not None)
不過,所有這些細節可能太多了-要點是,當您使用apply()
,您實際上不應該在要應用的函數中進行所有更改-您應該從函數返回一個結果,然后將它們分配回數據框,例如:
# The lambda here will return the relevant values of gate and pop,
# and we just assign them wherever we want in the dataframe.
# Could be new columns, could be existing ones
frame[['gate', 'pop']] = frame.groupby('year')[['gate', 'pop']].apply(
lambda group: group - group.mean(axis=0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.