【发布时间】:2021-01-19 07:03:29
【问题描述】:
我正在尝试获取每行倒数第二个非空列,其中空值可以在任何列中。由于 null 可以在任何地方,因此此类解决方案不起作用:Pandas select the second to last column which is also not nan
不是理想的解决方案: 我能够用下面的代码解决它,但必须有一种更简洁的方法来编写它。任何反馈将不胜感激。
data = [[1, 10, np.nan, np.nan], [2, 15, 13, np.nan], [9, 14, np.nan, np.nan]]
df = pd.DataFrame(data, columns = ['a', 'b', 'c', 'd'])
df['count_nulls'] = len(df.columns) - df.apply(lambda x: x.count(), axis=1)
df['count_nonnull'] = df.apply(lambda x: x.count(), axis=1)-1
df['new_index'] = np.where(df['count_nonnull']==1, 1,
np.where(df['count_nonnull']==0,0, df['count_nonnull'] - 1))
df['value'] = df.values[np.arange(len(df)), df['new_index']-1]
df
【问题讨论】: