【问题标题】:What is the Fastest way to compare values across columns in pandas (Python)在熊猫(Python)中比较列值的最快方法是什么
【发布时间】:2022-06-15 23:56:44
【问题描述】:

我有以下数据框:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.array([[1, 1, 1, 1], [1, 1, np.nan, 1], [1, np.nan, 1, 1]]),
                    columns=['t', 't_1', 't_2', 't_3'])

实际上有大约 1000 万行。 我需要一种快速的方法来知道哪个是最后一个具有非空值的连续列。 以这个 df 为例,结果将是 ->

df_result = pd.DataFrame(np.array([[1, 1, 1, 1], [1, 1, np.nan, np.nan], [1, np.nan, np.nan, np.nan]]),
                    columns=['t', 't_1', 't_2', 't_3'])

目前我正在使用以下 lambda 函数执行此操作,但结果太慢:

def second_to_last_null(*args):
    for i in range(len(args)):
        if np.isnan(args[i]):
            return np.nan
        else:
            return args[-1]


df_result['t'] = df['t']
df_result['t_1_consecutive'] = df[['t', 't_1']].apply(lambda x: second_to_last_null(x.t, x.t_1), axis=1)
df_result['t_2_consecutive'] = df[['t', 't_1', 't_2']].apply(lambda x: second_to_last_null(x.t, x.t_1, x.t_2), axis=1)
df_result['t_3_consecutive'] = df[['t', 't_1', 't_2', 't_3']].apply(lambda x: second_to_last_null(x.t, x.t_1, x.t_2, x.t_3), axis=1)

有人可以建议在 pandas/numpy 中执行此操作的最快方法吗? 关于为什么该方法比我的方法更好的简单技术解释也将不胜感激:)

【问题讨论】:

  • 你能用清晰的英语解释你想要做什么吗?从代码中并不完全清楚。

标签: python pandas


【解决方案1】:

isna 上尝试cumsum,然后mask

df.mask(df.isna().cumsum(axis=1) >= 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多