替代Pandas DataFrame中嵌套的np.where

K. *_*her 3 python numpy dataframe python-3.x pandas

我有这个代码(可以工作) - 一组嵌套的条件语句来设置数据帧的'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"))))
Run Code Online (Sandbox Code Playgroud)

要么;

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

jez*_*ael 7

一个可能的解决方案是使用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)
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法是使用带有 if-elif 语句和 pandas `apply` 的按行函数,如 /sf/answers/1273611391/ 中所述,但您的解决方案要快得多,@jezrael!谢谢你。 (2认同)