Pandas:获取 2 个数据框列之间的最小值 [英] Pandas: get the min value between 2 dataframe columns

查看:254
本文介绍了Pandas:获取 2 个数据框列之间的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 列,我希望第 3 列是它们之间的最小值.我的数据如下所示:

I have 2 columns and I want a 3rd column to be the minimum value between them. My data looks like this:

   A  B
0  2  1
1  2  1
2  2  4
3  2  4
4  3  5
5  3  5
6  3  6
7  3  6

我想通过以下方式得到一个 C 列:

And I want to get a column C in the following way:

   A  B   C
0  2  1   1
1  2  1   1
2  2  4   2
3  2  4   2
4  3  5   3
5  3  5   3
6  3  6   3
7  3  6   3

一些帮助代码:

df = pd.DataFrame({'A': [2, 2, 2, 2, 3, 3, 3, 3],
                   'B': [1, 1, 4, 4, 5, 5, 6, 6]})

谢谢!

推荐答案

使用 df.min(axis=1)

df['c'] = df.min(axis=1)
df
Out[41]: 
   A  B  c
0  2  1  1
1  2  1  1
2  2  4  2
3  2  4  2
4  3  5  3
5  3  5  3
6  3  6  3
7  3  6  3

这将返回最小行(当传递 axis=1 时)

This returns the min row-wise (when passing axis=1)

对于非异构数据类型和大型 dfs,您可以使用 numpy.min 会更快:

For non-heterogenous dtypes and large dfs you can use numpy.min which will be quicker:

In[42]:
df['c'] = np.min(df.values,axis=1)
df

Out[42]: 
   A  B  c
0  2  1  1
1  2  1  1
2  2  4  2
3  2  4  2
4  3  5  3
5  3  5  3
6  3  6  3
7  3  6  3

时间:

In[45]:
df = pd.DataFrame({'A': [2, 2, 2, 2, 3, 3, 3, 3],
                   'B': [1, 1, 4, 4, 5, 5, 6, 6]})
df = pd.concat([df]*1000, ignore_index=True)
df.shape

Out[45]: (8000, 2)

所以对于 8K 行 df:

So for a 8K row df:

%timeit df.min(axis=1)
%timeit np.min(df.values,axis=1)
314 µs ± 3.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
34.4 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

你可以看到 numpy 版本快了将近 10 倍(注意我传递了 df.values 所以我们传递了一个 numpy 数组),当我们得到更大的 dfs 时,这将变得更加重要

You can see that the numpy version is nearly 10x quicker (note I pass df.values so we pass a numpy array), this will become more of a factor when we get to even larger dfs

注意

对于 0.24.0 或更高版本,请使用 to_numpy()

for versions 0.24.0 or greater, use to_numpy()

所以上面变成:

df['c'] = np.min(df.to_numpy(),axis=1)

时间:

%timeit df.min(axis=1)
%timeit np.min(df.values,axis=1)
%timeit np.min(df.to_numpy(),axis=1)
314 µs ± 3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
35.2 µs ± 680 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
35.5 µs ± 262 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

.valuesto_numpy() 之间存在细微差异,这取决于您是否事先知道 dtype 不是混合的,并且可能的 dtype 是一个因素,例如float 16float 32 请参阅该链接以获取进一步说明.Pandas 在调用 to_numpy

There is a minor discrepancy between .values and to_numpy(), it depends on whether you know upfront that the dtype is not mixed, and that the likely dtype is a factor e.g. float 16 vs float 32 see that link for further explanation. Pandas is doing a little more checking when calling to_numpy

这篇关于Pandas:获取 2 个数据框列之间的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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