代码之家  ›  专栏  ›  技术社区  ›  00__00__00

如何在混合数据类型数据帧中仅聚合数字列

  •  2
  • 00__00__00  · 技术社区  · 8 年前

    我有一个混合的 pd.DataFrame :

    import pandas as pd
    import numpy as np
    df = pd.DataFrame({ 'A' : 1.,
                         'B' : pd.Timestamp('20130102'),
                         'C' : pd.Timestamp('20180101'),
                         'D' : np.random.rand(10),
                         'F' : 'foo' })
    
    df
    Out[12]: 
         A          B          C         D    F
    0  1.0 2013-01-02 2018-01-01  0.592533  foo
    1  1.0 2013-01-02 2018-01-01  0.819248  foo
    2  1.0 2013-01-02 2018-01-01  0.298035  foo
    3  1.0 2013-01-02 2018-01-01  0.330128  foo
    4  1.0 2013-01-02 2018-01-01  0.371705  foo
    5  1.0 2013-01-02 2018-01-01  0.541246  foo
    6  1.0 2013-01-02 2018-01-01  0.976108  foo
    7  1.0 2013-01-02 2018-01-01  0.423069  foo
    8  1.0 2013-01-02 2018-01-01  0.863764  foo
    9  1.0 2013-01-02 2018-01-01  0.037085  foo
    

    我想聚合我的数字列,但也保留非数字列。 gropuby agg 我得到:

    df.groupby('B').agg(np.median)
    Out[13]: 
                  A         D
    B                        
    2013-01-02  1.0  0.482157
    

    F 有价值的 foo 以及 C 具有 2018-01-01

    到目前为止,我已经用一个自定义包装器解决了我的数值聚合函数问题,例如,如果我想在我的数据帧上执行nanmean:

    def my_nan_median(x):
        if isinstance(x.values[0], np.datetime64):
            return np.min(x) # let the first datetime pass! 
        elif isinstance(x.values[0], str):
            return x.values[0] # let the strings pass!
        else:
            return np.nanmedian(x) 
    

    正确的方法是什么?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Brad Solomon    8 年前

    通过使用 select_dtypes :

    df.groupby(list(df.select_dtypes(exclude=[np.number]))).agg(np.median).reset_index()
    

    或者类似这样:

    df1 = df.groupby('B',as_index=False).agg(np.median)
    pd.concat([df1,df.drop_duplicates(['B']).drop(list(df1),1).reset_index(drop=True)],axis=1)
    
        2
  •  3
  •   Scott Boston    8 年前

    如果“C”、“F”对于“B”的每个值都相同,则可以将其包括在groupby列中,如下所示:

    df.groupby(['B','C','F']).agg(np.median).reset_index()
    

    df.groupby(['B','C','F'], as_index=False).agg(np.median)
    

    输出:

               B          C    F    A         D
    0 2013-01-02 2018-01-01  foo  1.0  0.392723
    

    如果不是,那么您需要以某种方式聚合“C”,“F”,例如从“C”,“F”中获取第一个值

    df.groupby('B').agg({'D':np.median,'A':np.median,'C':'first','F':'last'}).reset_index() 
    
               B          C    F    A         D
    0 2013-01-02 2018-01-01  foo  1.0  0.392723