[英]Selecting a sub-set of the dataframe in the second level of the pandas multiindex
[英]More efficient way to mean center a sub-set of columns in a pandas dataframe and retain column names
我有一個大約有 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)
關於如何提高效率/更快的任何建議都會很棒!
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
我知道這個問題有點老,但現在 Scikit 是最快的解決方案。 另外,您可以將代碼壓縮在一行中:
pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)
%timeit pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)
684 µs ± 30.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
test.subtract(df.mean())
%timeit df.subtract(df.mean())
1.63 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
我用於測試的df:
df = pd.DataFrame(np.random.randint(low=1, high=10, size=(20,5)),columns = list('abcde'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.