【问题标题】:Select the rows with maximum non na columns from a continuous set of of n rows从一组连续的 n 行中选择具有最大非 na 列的行
【发布时间】:2021-09-02 12:56:57
【问题描述】:

我有一个带有时间索引的 df,以及一些带有数值的列,但在某些情况下也包含缺失值。 例如:

timeindex   ColA    ColB    ColC
00:02:00      454    436    4334
00:04:00             653
00:06:00      3423   4354 
00:08:00      3432
00:10:00      2343
00:12:00     32432          23423

我想创建数据框的一个子集,这样对于每 3 行的连续组,它会选择缺失值数量最少的行。 所以对于上面的 df,subsetdf 看起来像:

timeindex   ColA    ColB    ColC
00:02:00      454    436    4334
00:12:00     32432          23423

请您告诉我如何实现这一目标

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    使用df.filter 选择列,检查空字符串,在轴1 上使用sum,最后使用groupby.idxmax

    idx = (df.assign(count=df.filter(like="Col").notnull().sum(1))
             .groupby(np.arange(len(df))//3)["count"].idxmax())
    
    print (df.loc[idx])
    
      timeindex   ColA ColB   ColC
    0  00:02:00    454  436   4334
    5  00:12:00  32432       23423
    

    【讨论】:

    • TypeError: cannot perform floordiv with this index type: Index
    • 然后用np.arange(len(df))//3代替df.index//3。
    • 由于某种原因,输出没有选择具有最低空值列的行......它只是选择每 3 行组的第 3 行
    • 空值为nan
    • 那你为什么要提供一个带有空值的示例df?如果只是 nan 会简单得多。
    【解决方案2】:
    # split the dataframe into groups of 3
    df_dict = {n: df.iloc[n:n+3, :] 
               for n in range(0, len(df), 3)}
    
    # find indexes of the minimum number of None for each group
    mask = []
    for g in df_dict.values():
        mask.append((g.isnull().sum(axis=1)).idxmin())
    
    # keep only those rows
    df.iloc[mask]
    

    如果你想清空而不是无:

    替换这一行:

    mask.append((g.isnull().sum(axis=1)).idxmin())
    

    通过这一行:

    mask.append((g.eq('').sum(axis=1)).idxmin())
    

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2018-12-16
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多