【问题标题】:Alternative to nested np.where in Pandas DataFramePandas DataFrame 中嵌套 np.where 的替代方案
【发布时间】:2018-08-21 12:29:10
【问题描述】:

我有这段代码(有效) - 一组嵌套条件语句用于设置数据帧 (myOxides['cpx']) 的 'paragenesis1' 行中的值,具体取决于帧的其他各种行中的值。
我对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"))))

【问题讨论】:

  • 你能添加一些示例数据并尝试将其更改为最小工作示例吗?

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


【解决方案1】:

一种可能的解决方案是使用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)

【讨论】:

  • 效果惊人! - 我显然有很多东西要学。非常感谢。
  • 另一种方法是使用带有 if-elif 语句和 pandas apply 的逐行函数,如 stackoverflow.com/a/18194448/1936114 中所述,但您的解决方案要快得多,@jezrael!谢谢。
  • 在我的例子中,这是嵌套 np.where 速度的 X200 倍。有关string 类型列操作,请参见此处。
猜你喜欢
  • 2022-12-22
  • 2021-06-06
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 2017-09-03
  • 2020-08-18
  • 2021-05-25
相关资源
最近更新 更多