Skip to main content
 首页 » 编程设计

python之如何在不使用where函数的情况下根据pandas DataFrame下的其他列有条件地选择列

2025年05月04日10dudu

我在 python 2.5 下工作(由于外部 api,我仅限于该版本)并希望获得与我在 python 2.7 下编写的代码相同的结果

import pandas as pd 
df = pd.DataFrame({"lineId":[1,2,3,4], "idCaseMin": [10, 23, 40, 8], "min": [-110, -205, -80, -150], "idCaseMax": [5, 27, 15, 11], "max": [120, 150, 110, 90]}) 
df = df.set_index("lineId") 
 
df["idMax"] = df["idCaseMax"].where(df["max"]>abs(df["min"]),df["idCaseMin"]) 

DataFrame 结果:

>>> df 
        idCaseMax  max  idCaseMin  min  idMax 
lineId                                        
1               5   10        120 -110      5 
2              27   23        150 -205     23 
3              15   40        110  -80     15 
4              11    8         90 -150      8 

idMax column 是根据获得最大值的 id 定义的,在绝对模块中,在 max 内和 min列。

我不能使用 where功能,因为它在 pandas 0.9.0 下不可用(最新版本可用于 python 2.5 )和 numpy 1.7.1 .

那么,我必须选择哪些选项才能获得 idMax 的相同结果?列而不使用 pandas where功能?

请您参考如下方法:

您可以使用 IIUC numpy.where() :

In [120]: df['idMax'] =  \ 
              np.where(df["max"]<=abs(df["min"]), 
                       df["idCaseMin"], 
                       df["idCaseMax"]) 
 
In [121]: df 
Out[121]: 
        idCaseMax  idCaseMin  max  min  idMax 
lineId 
1               5         10  120 -110      5 
2              27         23  150 -205     23 
3              15         40  110  -80     15 
4              11          8   90 -150      8