【问题标题】:Pandas apply (path-dependent)Pandas 应用(依赖于路径)
【发布时间】:2022-10-16 01:59:02
【问题描述】:

在 pandas 中矢量化路径相关函数(即中间结果取决于先前结果的函数)的有效方法是什么?将结果存储在矩阵中并对先前的结果进行索引不会提高 for 循环的性能。

a,b->f(x,y) 在以下数据帧上:

>>> pd.DataFrame({
    'a':   [1,3,5,7,7,7,4],
    'b':   [2,2,2,2,2,1,1],
    'f(xy):[1,1,3,5,5,6,5],
})
   a  b  f(xy)
0  1  2  1
1  3  2  1
2  5  2  3
3  7  2  5
4  7  2  5
5  7  1  6
6  4  1  5

函数在哪里(元语言):

if t==0
    f(xy[t]) = a[t]

else:

    if f(xy[t-1]) < a[t]-b[t]:
        f(xy[t]) = a[t]-b[t]

    else if f(xy[t-1]) > a[t-1]+b[t]:
        f(xy[t]) = a[t]+b[t]

    else:
        f(xy[t]) = xy[t-1]

(t 是数据帧索引)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用您提供的数据框:

    import pandas as pd
    
    df = pd.DataFrame(
        {
            "a": [1, 3, 5, 7, 7, 7, 4],
            "b": [2, 2, 2, 2, 2, 1, 1],
        }
    )
    

    这是使用 Numpy where 的一种方法:

    import numpy as np
    
    # Setup
    df["f(xy)"] = 0
    
    # General case
    df["f(xy)"] = np.where(
        (df["f(xy)"].shift(-1) < df["a"] - df["b"]),
        df["a"] - df["b"],
        np.where(
            (df["f(xy)"].shift(-1) > df["a"] - df["b"]),
            df["a"] + df["b"],
            df["f(xy)"].shift(-1),
        ),
    )
    
    # First row
    df.at[0, "f(xy)"] = df.loc[0, "a"]
    # df.at[df.shape[0]-1, "f(xy)"] = df.apply(lambda x: , axis=1)
    
    # Last row
    df.at[df.shape[0] - 1, "f(xy)"] = np.where(
        (
            df.loc[df.shape[0] - 2, "f(xy)"]
            < df.loc[df.shape[0] - 1, "a"] - df.loc[df.shape[0] - 1, "b"]
        ),
        df.loc[df.shape[0] - 1, "a"] - df.loc[df.shape[0] - 1, "b"],
        np.where(
            (
                df.loc[df.shape[0] - 2, "f(xy)"]
                > df.loc[df.shape[0] - 1, "a"] - df.loc[df.shape[0] - 1, "b"]
            ),
            df.loc[df.shape[0] - 1, "a"] + df.loc[df.shape[0] - 1, "b"],
            df.loc[df.shape[0] - 2, "f(xy)"],
        ),
    )
    
    print(df)
    # Output
       a  b  f(xy)
    0  1  2    1.0
    1  3  2    1.0
    2  5  2    3.0
    3  7  2    5.0
    4  7  2    5.0
    5  7  1    6.0
    6  4  1    5.0
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 2017-11-28
      • 1970-01-01
      相关资源
      最近更新 更多