所选行和列的 pandas min() [英] Pandas min() of selected row and columns

查看:86
本文介绍了所选行和列的 pandas min()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一列,该列仅包含一行的最小值和几列,例如:

I am trying to create a column which contains only the minimum of the one row and a few columns, for example:

    A0      A1      A2      B0      B1      B2      C0      C1
0   0.84    0.47    0.55    0.46    0.76    0.42    0.24    0.75
1   0.43    0.47    0.93    0.39    0.58    0.83    0.35    0.39
2   0.12    0.17    0.35    0.00    0.19    0.22    0.93    0.73
3   0.95    0.56    0.84    0.74    0.52    0.51    0.28    0.03
4   0.73    0.19    0.88    0.51    0.73    0.69    0.74    0.61
5   0.18    0.46    0.62    0.84    0.68    0.17    0.02    0.53
6   0.38    0.55    0.80    0.87    0.01    0.88    0.56    0.72

在这里,我试图创建一列,其中包含B0,B1,B2列每一行的最小值.

Here I am trying to create a column which contains the minimum for each row of columns B0, B1, B2.

输出看起来像这样:

    A0      A1      A2      B0      B1      B2      C0      C1      Minimum
0   0.84    0.47    0.55    0.46    0.76    0.42    0.24    0.75    0.42
1   0.43    0.47    0.93    0.39    0.58    0.83    0.35    0.39    0.39
2   0.12    0.17    0.35    0.00    0.19    0.22    0.93    0.73    0.00
3   0.95    0.56    0.84    0.74    0.52    0.51    0.28    0.03    0.51
4   0.73    0.19    0.88    0.51    0.73    0.69    0.74    0.61    0.51
5   0.18    0.46    0.62    0.84    0.68    0.17    0.02    0.53    0.17
6   0.38    0.55    0.80    0.87    0.01    0.88    0.56    0.72    0.01

这是代码的一部分,但是没有按照我想要的去做:

Here is part of the code, but it is not doing what I want it to do:

for i in range(0,2):
    df['Minimum'] = df.loc[0,'B'+str(i)].min()

推荐答案

这是一个单行代码,您只需要对min使用axis自变量来告诉它跨列而不是向下运行:

This is a one-liner, you just need to use the axis argument for min to tell it to work across the columns rather than down:

df['Minimum'] = df.loc[:, ['B0', 'B1', 'B2']].min(axis=1)

如果需要将此解决方案用于不同数量的列,则可以使用for循环或列表理解来构造列列表:

If you need to use this solution for different numbers of columns, you can use a for loop or list comprehension to construct the list of columns:

n_columns = 2
cols_to_use = ['B' + str(i) for i in range(n_columns)]
df['Minimum'] = df.loc[:, cols_to_use].min(axis=1)

这篇关于所选行和列的 pandas min()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆