熊猫:获取2个数据框列之间的最小值

Adr*_*ian 9 python min dataframe python-3.x pandas

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

   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
Run Code Online (Sandbox Code Playgroud)

我想通过以下方式获取列C:

   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
Run Code Online (Sandbox Code Playgroud)

一些帮助代码:

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

谢谢!

EdC*_*ica 13

使用 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
Run Code Online (Sandbox Code Playgroud)

返回行的最小值(传递时axis=1

对于非异构dtype和大df,可以使用numpy.min更快的方法:

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
Run Code Online (Sandbox Code Playgroud)

时间

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)
Run Code Online (Sandbox Code Playgroud)

因此,对于8K行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)
Run Code Online (Sandbox Code Playgroud)

您可以看到numpy版本快了近10倍(请注意,我通过了,df.values所以我们传递了一个numpy数组),当我们使用更大的dfs时,这将成为一个更大的因素

注意

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

所以上面变成:

df['c'] = np.min(df.to_numpy(),axis=1)
Run Code Online (Sandbox Code Playgroud)

时间

%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)
Run Code Online (Sandbox Code Playgroud)

.values和之间存在细微的差异to_numpy(),这取决于您是否预先知道dtype没有混合,并且可能的dtype是一个因素,例如,float 16vs float 32请参阅该链接以获取进一步的说明。熊猫在打电话时会做更多检查to_numpy

  • 小注释,对于熊猫0.24.0或更高版本,`df.to_numpy()`比`df.values`更可取 (2认同)