[英]Move last non-null value of each row - Pandas
我正在研究 dataframe ,它來自 noSQL 表,這意味着行的長度不同。 我需要檢索每行的最后一個非空值,將其移動到新列“h”並將其從其初始 position 中刪除。
我最初的 DataFrame 是:
a b c d e f g
0 1635 01/01/2018 Null Null 95 120 80
1 7364 01/15/2018 178 182 99 Null Null
2 8947 01/20/2018 Null 190 92 Null Null
3 6473 01/24/2018 45 122 99 32 Null
我想得到這個結果:
a b c d e f g h
0 1635 01/01/2018 Null Null 95 120 Null 80
1 7364 01/15/2018 178 182 Null Null Null 99
2 8947 01/20/2018 Null 190 Null Null Null 92
3 6473 01/24/2018 45 122 99 Null Null 32
Use, DataFrame.ne
along with DataFrame.cumsum
and DataFrame.idxmax
along axis=1
to get the columns containing the last non null value, finally use DataFrame.lookup
to get the values, corresponding to the cols
:
cols = df.ne('Null').cumsum(axis=1).idxmax(axis=1)
df['h'] = df.lookup(df.index, cols)
結果:
# print(df)
a b c d e f g h
0 1635 01/01/2018 Null Null 95 120 80 80
1 7364 01/15/2018 178 182 99 Null Null 99
2 8947 01/20/2018 Null 190 92 Null Null 92
3 6473 01/24/2018 45 122 99 32 Null 32
作為其他解決方案,您可以使用last_valid_index 。 但是,您首先必須將所有Null
值轉換為np.NaN
。
df[df=="Null"] = np.NaN
df["h"] = df.apply(lambda x: x[x.last_valid_index()], axis=1)
df
Output:
a b c d e f g h
0 1635 01/01/2018 95 120 80 80
1 7364 01/15/2018 178 182 99 99
2 8947 01/20/2018 190 92 92
3 6473 01/24/2018 45 122 99 32 32
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.