熊猫选择倒数第二列,也不是南

时间:2016-06-21 22:56:08

标签: python pandas select nan

我尽可能地清理了我的数据并在Pandas数据框中阅读它们。所以问题是不同的文件具有不同的列数,但它总是第二个到最后一个非纳米列是我想要的。那么有没有把它们拿出来?这是一个数据示例。

     ...    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列的数量。但它始终是最后一个非纳米柱的第二个是我需要的。感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

与@piRSquared类似的想法。基本上,使用loc保留非空列,然后使用iloc选择倒数第二列。

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

答案 1 :(得分:1)

一个班轮

df.loc[:, :df.columns[(df.columns == df.isnull().all().idxmax()).argmax() - 2]]

   ...      f       g
0  ...  39994  29.568
1  ...  39994  29.568
2  ...  39994  29.568

可读

# identify null columns
nullcols = df.isnull().all()

# find the column heading for the first null column
nullcol = nullcols.idxmax()

# where is null column at
nullcol_position = (df.columns == nullcol).argmax()

# get column 2 positions prior
col_2_prior_to_null_col = df.columns[nullcol_position - 2]

# get dataframe
print df.loc[:, :col_2_prior_to_null_col]