从n行的连续集合中选择具有最大非na列的行

2024-06-16 11:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有时间索引的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

我想创建dataframe的一个子集,这样对于每一个连续的3行组,它都会选择丢失值最少的行。 因此,对于上述df,子TDF如下所示:

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

你能告诉我怎样才能做到这一点吗


Tags: dataframedf时间情况子集数值tdfcolc
2条回答

使用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
# 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())

相关问题 更多 >