替代Pandas DataFrame中嵌套的np.where

时间:2018-03-13 09:50:06

标签: python python-3.x pandas numpy dataframe

我有这个代码(有效) - 一堆嵌套的条件语句来设置' paragenesis1'数据帧的一行(myOxides [' cpx']),具体取决于框架的其他各行中的值。

一般来说,我对python和编程都很陌生。我在想我应该编写一个函数来执行此操作,但是如何应用元素元素呢?这是我发现避免一系列真值的模糊不清的唯一方法。错误。

任何帮助非常感谢!

myOxides['cpx'].loc['paragenesis1'] = np.where(
            ((cpxCrOx>=0.5) & (cpxAlOx<=4)),
            "GtPeridA", 
            np.where(
                    ((cpxCrOx>=2.25) & (cpxAlOx<=5)), 
                    "GtPeridB", 
                    np.where(
                            ((cpxCrOx>=0.5)&
                             (cpxCrOx<=2.25)) &
                             ((cpxAlOx>=4) & (cpxAlOx<=6)),
                             "SpLhzA",
                             np.where(
                                     ((cpxCrOx>=0.5) &
                                      (cpxCrOx<=(5.53125 - 
                                                 0.546875 * cpxAlOx))) &
                                      ((cpxAlOx>=4) & 
                                       (cpxAlOx <= ((cpxCrOx - 
                                                     5.53125)/ -0.546875))),
                             "SpLhzB",
                             "Eclogite, Megacryst, Cognate"))))

或;

df.loc['a'] = np.where(
            (some_condition),
            "value", 
            np.where(
                    ((conditon_1) & (condition_2)), 
                    "some_value", 
                    np.where(
                            ((condition_3)& (condition_4)),
                             "some_other_value",
                              np.where(
                                      ((condition_5),
                                        "another_value",
                                        "other_value"))))

1 个答案:

答案 0 :(得分:6)

一种可能的解决方案是使用numpy.select

m1 = (cpxCrOx>=0.5) & (cpxAlOx<=4)
m2 = (cpxCrOx>=2.25) & (cpxAlOx<=5)
m3 = ((cpxCrOx>=0.5) & (cpxCrOx<=2.25)) & ((cpxAlOx>=4) & (cpxAlOx<=6))
m4 = ((cpxCrOx>=0.5) &(cpxCrOx<=(5.53125 -  0.546875 * cpxAlOx))) & \
     ((cpxAlOx>=4) &  (cpxAlOx <= ((cpxCrOx -  5.53125)/ -0.546875))

vals = [ "GtPeridA", "GtPeridB", "SpLhzA", "SpLhzB"]
default = 'Eclogite, Megacryst, Cognate'

myOxides['paragenesis1'] = np.select([m1,m2,m3,m4], vals, default=default)