pandas 选择倒数第二列也不是 nan [英] Pandas select the second to last column which is also not nan
问题描述
我已经尽可能多地清理了我的数据,并在 Pandas 数据框中读取了它们.所以问题是不同的文件有不同的列数,但它总是倒数第二个非 nan 列是我想要的.那么有没有办法把它们挑出来呢?这是数据的示例.
I've cleaned my data as much as I can and read them in Pandas dataframe. So the problem is that different files have different number of columns, but it always the second to the last non-nan column is what I want. So is there anyway to pick them out? Here is an example of the data.
... f g h l
0 ... 39994 29.568 29.569 NaN
1 ... 39994 29.568 29.569 NaN
2 ... 39994 29.568 29.569 NaN
所以在这种情况下我想要列 g.所以在其他文件中,它可能是 f 或任何取决于最后 nan 列的数量.但它总是倒数第二个非 nan 列是我需要的.感谢您的帮助.
so I want the column g in this case. So in other files, it could be f or anything depends on the number of nan columns in the end. But it's always the second to the last non-nan column is what I need. Thanks for the help ahead.
推荐答案
与 @piRSquared 类似的想法.本质上,使用 loc
保留非空列,然后使用 iloc
选择倒数第二个.
Similar idea to @piRSquared. Essentially, use loc
to keep the non-null columns, then use iloc
to select the second to last.
df.loc[:, ~df.isnull().all()].iloc[:, -2]
样本输入:
a b c d e f g h i j
0 0 3 6 9 12 15 18 21 NaN NaN
1 1 4 7 10 13 16 19 22 NaN NaN
2 2 5 8 11 14 17 20 23 NaN NaN
示例输出:
0 18
1 19
2 20
Name: g, dtype: int32
这篇关于 pandas 选择倒数第二列也不是 nan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!