【问题标题】:Pandas select the second to last column which is also not nan熊猫选择倒数第二列,这也不是 nan
【发布时间】:2016-10-23 16:18:18
【问题描述】:

我已尽我所能清理我的数据并在 Pandas 数据框中读取它们。所以问题是不同的文件有不同的列数,但它总是倒数第二个非 nan 列是我想要的。那么有没有办法把它们挑出来?以下是数据示例。

     ...    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 列是我需要的。感谢您的帮助。

【问题讨论】:

    标签: python pandas select nan


    【解决方案1】:

    与@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
    

    【讨论】:

    • 谢谢,这正是我想要的。
    【解决方案2】:

    一个班轮

    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]
    

    【讨论】:

    • 这很好解释,非常感谢。但根的回答给了我我想要的。很抱歉....我必须选择root的解决方案。
    • 没问题。 @root 的答案更好。立即投票。
    猜你喜欢
    • 2021-07-10
    • 2023-03-19
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多