python - 如何将 agg 应用于具有根据级别不同功能的多索引的数据框?

标签 python pandas dataframe

我想根据索引的第二级对具有多重索引的数据帧应用不同的函数。

例如,对于数据框:

In [4]: df = pd.DataFrame({'a': [1,2,6,7],'b': [7,1,4,5]}, index = pd.MultiIndex.from_tuples( 
   ...:     [('x','tmax'),('x','tmin'),('y','tmax'), ('y','tmin')]))                                                          

In [5]: df                                                                                                                    
Out[5]: 
        a  b
x tmax  1  7
  tmin  2  1
y tmax  6  4
  tmin  7  5     

我想在索引为(-, tmax)时获得该行的最大值,在索引为(-, tmin)时获得该行的最小值,例如:

        value
x tmax      7
  tmin      1
y tmax      6
  tmin      5

我尝试过使用 agg,但我不知道如何根据多重索引的值应用 max 和 min 函数:

df.agg({'tmax': np.max, 'tmin': np.min}, axis = 1)

最佳答案

使用concatDataFrame.xs和聚合函数:

s = pd.concat([df.xs('tmax', level=1, drop_level=False).max(1),
               df.xs('tmin', level=1, drop_level=False).min(1)]).sort_index()
print (s)
x  tmax    7
   tmin    1
y  tmax    6
   tmin    5
dtype: int64

或者如果只有值 tmaxtmin 使用 numpy.where,则按第二级过滤:

m = df.index.get_level_values(1) == 'tmax'

s = pd.Series(np.where(m, df.max(1), df.min(1)), index=df.index)
print (s)
x  tmax    7
   tmin    1
y  tmax    6
   tmin    5
dtype: int64

关于python - 如何将 agg 应用于具有根据级别不同功能的多索引的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624878/

相关文章:

python - Pandas 中不规则时间序列的下采样

Python/Pandas - 合并基于非索引列的两个数据框

group-by - 时间石斑鱼、 Pandas

python - 列中的连接值取决于特定条件

python - 值错误 : No axis named node2 for object type <class 'pandas.core.frame.DataFrame' >

python - OSX 中的 Sklearn 安装

python - 如何在AWS Elastic MapReduce上使用Python流创建 “side-effect”文件?

python - 安排 python 的 sorted(set( <collection> ))

java - 为什么 java String.length 给出与相同字符串的 python len() 不同的结果

python - 计算多列的百分比