用NaN替换某些数据帧值

2024-06-07 02:42:23 发布

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

为了澄清问题,我对这个问题做了一些修改。 我有这样一个数据帧:

ID (index col)   1   1   1   1   1   2   2   2   2   2   3   3   3   3   3

其中ID列是strings,而df的其余部分是floats。与this question一样,我的目标是创建一个包含3列的新数据帧,其中每列是原始数据帧中3列的平均值,如下所示:

ID (index)    1avg   2avg   3avg

这个问题处理grouby调用,但在我这样做之前,我想检查确保在每一行中,每个子组中至少有2/3有一个实值。因此,我需要检查以下内容:

ID   1      1       1        1        1     2   2   2   2   2  3   3   3...
a   0.0005  0.0005  0.0005  0.0005  0.0005  7   5   2   19  5  18  9   20
b   0.0005  25      0.0005  0.0005    85    5   2   1   24  2  17  10  6
c   92      42      12      0.0005    15    1   2   5   52  2  3   5   7 
d   25      35      11      81        12    5   6   8   2   6  23  3   5

生成数据的程序(商业)用0.0005替换真正缺少的值,这也很难用NaN替换

我真正需要的是一种处理问题的方法

1)对于在所有子组列(上面的a行)中具有NAN的行,不应该发生任何事情,但我不能删除NAN,因为我需要在组之间保持相同的行数。当我平均所有的NaN时,平均值将保持NaN,这是理想的

2)对于至少3列中包含NaN的行(上面的b行),我需要将25和85转换为NaN,这样当我取平均值时,它将是NaN,但该行将保留,并且具有值的其他组将不受影响

3)对于具有1或2个NAN的行(上面的c行)或所有列中具有值的行(上面的d行),它们应保持原样以获得平均值


Tags: 数据id目标df原始数据indexcolnan
1条回答
网友
1楼 · 发布于 2024-06-07 02:42:23

好的,我最终找到了一个解决方案,但我仍然有兴趣知道是否有人能提出更好/更正确的方法

concentrations = ['1','2','3'...]
for k in concentrations:
tf = df[k]

for index,row in tf.iterrows():
    counter = 0
    for item in row:
        if math.isnan(item) == True:
            counter = counter+1

        if counter >2: #where 2 is the number of NaNs I'll let remain before I replace the row with NaNs
            tf.at[index] = np.nan

#also pretty unclear if all of this is necessary but it works
tfnew = tf.groupby(by=tf.columns, axis=1).apply(lambda g: g.mean(axis=1) if isinstance(g.iloc[0,0], numbers.Number) else g.iloc[:,0])           
ultra[k] = tfnew[k]

相关问题 更多 >