2016-01-22 66 views
2

我有一個大約有370列的數據框。我正在測試一系列要求我使用模型的子集來擬合三次迴歸模型的假設。我正在計劃使用statsmodels來模擬這些數據。更有效的方式來表示在熊貓數據框中居中列的子集並保留列名稱

多項式迴歸過程的一部分涉及平均居中變量(從特定特徵的每種情況中減去均值)。

我可以用3行代碼做到這一點,但它似乎效率低下,因爲我需要複製這個過程的半打假設。請記住,我需要從statsmodel輸出的係數級數據,所以我需要保留列名。

這是對數據的窺視。 這是我爲我的一個假設測試所需的列的子集。

 i we you shehe they ipron 
0 0.51 0 0 0.26 0.00 1.02 
1 1.24 0 0 0.00 0.00 1.66 
2 0.00 0 0 0.00 0.72 1.45 
3 0.00 0 0 0.00 0.00 0.53 

這是代表中心並保留列名稱的代碼。

from sklearn import preprocessing 
#create df of features for hypothesis, from full dataframe 
h2 = df[['i', 'we', 'you', 'shehe', 'they', 'ipron']] 

#center the variables 
x_centered = preprocessing.scale(h2, with_mean='True', with_std='False') 

#convert back into a Pandas dataframe and add column names 
x_centered_df = pd.DataFrame(x_centered, columns=h2.columns) 

任何關於如何使這個更高效/更快的建議將會非常棒!

回答

2
df.apply(lambda x: x-x.mean()) 

%timeit df.apply(lambda x: x-x.mean()) 
1000 loops, best of 3: 2.09 ms per loop 

df.subtract(df.mean()) 

%timeit df.subtract(df.mean()) 
1000 loops, best of 3: 902 µs per loop 

都產生:

 i we you shehe they ipron 
0 0.0725 0 0 0.195 -0.18 -0.145 
1 0.8025 0 0 -0.065 -0.18 0.495 
2 -0.4375 0 0 -0.065 0.54 0.285 
3 -0.4375 0 0 -0.065 -0.18 -0.635 
+0

非常感謝! lambda函數效果很好。 Python解決方案非常簡單...我總是認爲他們會比他們總是變得更復雜。 再次感謝! –

+0

你知道爲什麼我從這種手術中獲得的意義不是零? –

+0

如果它非常接近於零(如e-15),那麼它就是浮動表示。如果它真的與零不同,那麼其他的東西就會關閉。例如嘗試:np.random.seed(42) values = np.random.randint(-100,100,50) np.mean(values -np.mean(values)),得到3.97903932026e-15。 – Stefan

相關問題