如何高效获取Pandas DataFrame每行的最后一个非空值?
如何高效获取Pandas DataFrame每行的最后一个非空值
问题场景
给定包含多列缺失值(None/NaN)的Pandas DataFrame,需要高效提取每行的最后一个非空值。
示例数据
import pandas as pd data = { "product_id": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], "col1": ["a", "a", "a", "a", "a", "a", "a", "a", "a"], "col2": ["b", None, "b", None, "b", None, "b", None, "b"], "col3": ["c", None, "c", None, None, None, None, None, None], "col4": [None, None, None, None, None, "d", None, None, "d"] } df = pd.DataFrame(data)
解决方案
方法1:Pandas内置简洁实现
利用bfill(axis=1)沿行方向从右向左填充缺失值,最后取每行的最后一列即可得到目标结果:
df['row_wise_last_non_nulls'] = df.bfill(axis=1).iloc[:, -1]
方法2:大数据集高效实现
如果处理超大DataFrame,使用numpy底层操作可以获得更好的性能:
import numpy as np # 生成非缺失值的掩码矩阵 mask = ~df.isna() # 找到每行最后一个非缺失值的列索引 last_non_null_cols = mask.cumsum(axis=1).idxmax(axis=1) # 通过索引匹配提取对应值 df['row_wise_last_non_nulls'] = df.lookup(df.index, last_non_null_cols)
预期输出
product_id col1 col2 col3 col4 row_wise_last_non_nulls 0 1 a b c None c 1 2 a None None None a 2 3 a b c None c 3 4 a None None None a 4 5 a b None None b 5 6 a None None d d 6 7 a b None None b 7 8 a None None None a 8 9 a b None d d
内容的提问来源于stack exchange,提问作者Soudipta Dutta
相关产品推荐
相关产品推荐

