【问题标题】:Applying sqrt function on a column在列上应用 sqrt 函数
【发布时间】:2016-09-12 09:32:42
【问题描述】:

我有以下数据框

data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
                'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'],
                'wins': [11, 8, 10, 15, 11, 6, 10, 4],
                'losses': [5, 8, 6, 1, 5, 10, 6, 12]}

football = pd.DataFrame(data, columns=['year', 'team', 'wins', 'losses'])
football.set_index(['team', 'year'], inplace=True)

对列求和后如何应用sqrt 函数?

football[['wins', 'losses']].sum(axis=1)

【问题讨论】:

    标签: python numpy pandas dataframe


    【解决方案1】:

    只需在生成的pd.Series 上使用numpy.sqrt() (see docs):

    import numpy as np
    np.sqrt(football[['wins', 'losses']].sum(axis=1))
    

    但是当然有几种方法可以实现相同的结果 - 请参阅下面的说明:

    df = pd.DataFrame.from_dict(data={'col_1': np.random.randint(low=1, high=10, size=10), 'col_2': np.random.randint(low=1, high=10, size=10)}, orient='index').T
    
    df['sum'] = df[['col_1', 'col_2']].sum(axis=1)
    df['np'] = np.sqrt(df[['col_1', 'col_2']].sum(axis=1))
    df['apply'] = df[['col_1', 'col_2']].sum(axis=1).apply(np.sqrt)
    df['**'] = df[['col_1', 'col_2']].sum(axis=1) ** .5
    
       col_1  col_2  sum        np     apply        **
    0      8      3   11  3.316625  3.316625  3.316625
    1      4      1    5  2.236068  2.236068  2.236068
    2      6      2    8  2.828427  2.828427  2.828427
    3      4      1    5  2.236068  2.236068  2.236068
    4      4      7   11  3.316625  3.316625  3.316625
    5      7      4   11  3.316625  3.316625  3.316625
    6      5      5   10  3.162278  3.162278  3.162278
    7      1      2    3  1.732051  1.732051  1.732051
    8      6      6   12  3.464102  3.464102  3.464102
    9      5      7   12  3.464102  3.464102  3.464102
    

    【讨论】:

      【解决方案2】:

      我是内置 pandas.DataFrame.pow(文档here)的个人粉丝。这样您就可以获得各种顺序的根(例如 Stefan 的最后一个示例)。

      football[['wins','losses']].sum(axis=1).pow(1./2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-14
        • 2013-06-22
        • 1970-01-01
        • 2017-08-02
        • 2012-05-26
        相关资源
        最近更新 更多