在 pandas 数据框的列中查找最小值和最大值

Find the minimum and maximum values in the columns of a pandas data frame

我确实找过和我类似的问题,但我仍然没有找到任何答案。

我有这样一个数据框:

          achaea    bacteria    plastids    mitochondrion   viruses
CTAG    -22.141701  -27.891441  -2.474725   0.262533    0.026349
GGCC    -13.403537  -21.490028  -0.403491   -0.271403   -0.243087
GATC    -20.933825  -14.761891  4.681494    -0.098965   0.088650
CATG    -8.490766   -9.910195   1.150736    -0.005730   0.508743
TAAG    -17.376165  -18.653078  -1.525354   -0.708633   -1.917676

我的疑问是:'如何从列中获取最小值和最大值?' 我想要这样的:

最小值:

archaea     CTAG  -22.141701 
bacteria    CTAG  -27.891441   
plastids    CTAG  -2.474725
mitochondrion   TAAG -0.708633
viruses    TAAG    -1.917676

最大值:

archaea     CATG    -8.4907661 
bacteria    CATG    -9.910195   
plastids    GATC  4.681494
mitochondrion   CTAG 0.262533
viruses    CATG    0.508743

我试过:

df.min()
achaea          -22.141701
bacteria        -27.891441
plastids         -4.654833
mitochondrion    -0.881587
viruses          -1.917676
dtype: float64

df['achaea'].idxmin()
'CTAG'

df.reset_index().min()
index                AAAA
achaea           -22.1417
bacteria         -27.8914
plastids         -4.65483
mitochondrion   -0.881587
viruses          -1.91768
dtype: object

好吧,我试过了,非常接近:

for col, idx in zip(df.columns, df.index):
    print(df[col].min(), idx, col)

-22.141701229820306 CTAG archaea
-27.89144069672985 GGCC bacteria
-4.654832775512324 GATC plastids
-0.8815871622500514 CATG mitochondrion
-1.917675731085761 TAAG viruses

您可以使用:

df.where(df.eq(df.min())).T.stack()
  • 确定列值等于每列的最小值
  • 屏蔽其他值
  • 在丢弃 NaN 的同时重塑堆栈(首先转置以更改顺序或索引)

输出:

achaea         CTAG   -22.141701
bacteria       CTAG   -27.891441
plastids       CTAG    -2.474725
mitochondrion  TAAG    -0.708633
viruses        TAAG    -1.917676
dtype: float64

一个有趣的选项是 agg,其中包含一个函数列表:

result = df.agg([min, max])

对于你的数据样本,我得到了:

        achaea   bacteria  plastids  mitochondrion   viruses
min -22.141701 -27.891441 -2.474725      -0.708633 -1.917676
max  -8.490766  -9.910195  4.681494       0.262533  0.508743

但如果您想要 min/max 个值 及其索引 ,则:

  1. 定义如下函数:

    def xx(col):
        iMin = col.idxmin()
        iMax = col.idxmax()
        return pd.Series([col[iMin], col[iMax]],
            index=[[col.name, col.name], [iMin, iMax]])
    
  2. 连接每列的结果:

    result = pd.concat([ xx(df[col]) for col in df ])
    

结果是:

achaea         CTAG   -22.141701
               CATG    -8.490766
bacteria       CTAG   -27.891441
               CATG    -9.910195
plastids       CTAG    -2.474725
               GATC     4.681494
mitochondrion  TAAG    -0.708633
               CTAG     0.262533
viruses        TAAG    -1.917676
               CATG     0.508743
dtype: float64

第一个索引级别显示列名。

第二层显示该栏的最小值/最大值的指标值。