从Python Pandas中的其他两个Series创建一个逐元素的最小Series [英] Creating an element-wise minimum Series from two other Series in Python Pandas

查看:389
本文介绍了从Python Pandas中的其他两个Series创建一个逐元素的最小Series的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到一种方法来对熊猫中的两个Series对象进行有效的元素级最小化.例如,我可以很容易地添加两个系列:

I am having trouble finding a way to do an efficient element-wise minimum of two Series objects in pandas. For example I can add two Series easily enough:

In [1]:
import pandas as pd
s1 = pd.Series(data=[1,1,1], index=[1,2,3])
s2 = pd.Series(data=[1,2,2,1], index=[1,2,3,4])
s1.add(s2)    
Out[1]:
1     2
2     3
3     3
4   NaN
dtype: float64

但是我找不到在两个Series之间进行元素最小化的有效方法(以及对齐索引和处理NaN值).

But I cannot find an efficient way to do an element-wise minimum between two Series (along with aligning the indices and handling NaN values).

没关系.有一个带有combin函数的逃生舱口,因此您可以放置​​任何按元素的函数:

In [2]:
s1 = pd.Series(data=[1,1,1], index=[1,2,3])
s2 = pd.Series(data=[1,2,2,1], index=[1,2,3,4])
s1.combine(s2, min, 0)
Out[2]:
1    1
2    1
3    1
4    0
dtype: int64

推荐答案

我能看到的最直接的方法是将它们放入DataFrame中,然后采用逐行最小值:

The most straightforward way I can see is to make them into a DataFrame and then take the row-wise min:

>>> print pandas.concat([s1, s2], axis=1).min(axis=1)
1    1
2    1
3    1
4    1
dtype: float64

这篇关于从Python Pandas中的其他两个Series创建一个逐元素的最小Series的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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