【问题标题】:Using pandas .shift on multiple columns with different shift lengths在具有不同移位长度的多列上使用 pandas .shift
【发布时间】:2021-08-21 04:37:31
【问题描述】:

我创建了一个函数,它解析数据帧的每一列,将相应列中的数据上移到第一个观察值(移过“-”),并将该列存储在字典中。然后我将字典转换回数据框以具有适当移动的列。该函数是可操作的,在 12x3000 数据帧上大约需要 10 秒。但是,将其应用于 12x25000 时,速度非常慢。我觉得有一种更好的方法可以提高速度 - 甚至可能是我缺少的 shift 函数的一个参数。感谢任何帮助。

def create_seasoned_df(df_orig):
    """
    Creates a seasoned dataframe with only the first 12 periods of a loan
    """
    df_seasoned = df_orig.reset_index().copy()
    temp_dic = {}
    for col in cols:
        to_shift = -len(df_seasoned[df_seasoned[col] == '-'])
        temp_dic[col] = df_seasoned[col].shift(periods=to_shift)
    df_seasoned = pd.DataFrame.from_dict(temp_dic, orient='index').T[:12]
    return df_seasoned

【问题讨论】:

  • 你能发布示例数据框和预期的输出吗?

标签: python pandas shift


【解决方案1】:

尝试将此代码与apply 一起使用:

def create_seasoned_df(df_orig):
    df_seasoned = df_orig.reset_index().apply(lambda x: x.shift(df_seasoned[col].eq('-').sum()), axis=0)
    return df_seasoned

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多