【问题标题】:More efficient way to mean center a sub-set of columns in a pandas dataframe and retain column names更有效的方式意味着在熊猫数据框中居中列子集并保留列名
【发布时间】:2016-04-29 11:35:47
【问题描述】:

我有一个大约有 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)

任何关于如何提高效率/速度的建议都很棒!

【问题讨论】:

    标签: python pandas machine-learning scikit-learn statsmodels


    【解决方案1】:
    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
    

    【讨论】:

    • 非常感谢! lambda 函数效果很好。 Python 解决方案非常简单......我总是假设它们会比它们总是变得更复杂。再次感谢!!!
    • 你知道为什么我从这样的操作中得到的平均值不为零吗?
    • 如果它非常接近于零(比如 e-15),那么它就是浮点表示。如果它真的与零不同,那么其他东西就会关闭。例如:np.random.seed(42) values = np.random.randint(-100, 100, 50) np.mean(values - np.mean(values)),得到 3.97903932026e−15。跨度>
    • 谢谢斯特凡!我假设了很多,但仍然觉得它很烦人,必须确保,特别是因为我必须显示我目前正在学习的课程的平均值 = 0。
    • 您可以查看处理这些问题的 np.isclose。
    【解决方案2】:

    我知道这个问题有点老了,但现在 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'))
    

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 1970-01-01
      • 2021-12-22
      • 2020-08-06
      • 2013-12-23
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多