通过在列中的两个值之间插值并分别计算中位数来填充 table 中的 nan 值

filling nan values in a table by interpolation between two values in a column and calculating the median, respectively

我有一个 pandas DataFrame,如下所示:

| ID | x | y   | z   |
| -- | - | --- | --- |
|  1 | 0 | nan | 36  |
|  1 | 1 | 12  | nan |
|  1 | 2 | nan | 38  |
|  1 | 3 | 11  | 37  |
|  2 | 0 | nan | 37  |
|  2 | 1 | nan | 37  |
|  2 | 2 | nan | nan |
|  2 | 3 | nan | nan |

我现在想按以下方式为每个 ID 填充 nan 值:

  1. 如果给定 ID 的值存在,则在后续值之间进行插值(即:当查看 ID 1 时:z 的值(在 x1 行中)就是我要查找的值。我有 x0 的 z 值, x2 和 x3, 但缺少 x1 对应的 z 值。因此我想通过在 x0 行和 x2 行中的 z 值之间进行插值来找到 z 的值(在 x1 行中)。
  2. 如果没有为 ID 提供任何值(即:ID 2 的所有 y 值都是 nan),我想计算整个列的中位数(即:所有 ID 的所有 y 值)并填充具有该中位数的 nan 值。

结果应该是一个 pandas DataFrame,其中所有 nan 值都由上述方案填充。但是,我是 pandas 的初学者,不知道如何解决这个问题以获得完整的 DataFrame。

使用Series.interpolate per groups for columns in list first, and then replace missing values by median in DataFrame.fillna:

cols = ['y','z']
median = df[cols].median()

df[cols] = (df.groupby('ID')[cols].transform(lambda x: x.interpolate())
              .fillna(median))

print (df)
   ID  x     y     z
0   1  0  11.5  36.0
1   1  1  12.0  37.0
2   1  2  11.5  38.0
3   1  3  11.0  37.0
4   2  0  11.5  37.0
5   2  1  11.5  37.0
6   2  2  11.5  37.0
7   2  3  11.5  37.0

此外,如果需要在 interpolation 中指定 limit_direction,请使用:

cols = ['y','z']
median = df[cols].median()

df[cols]= df.groupby('ID')[cols].transform(lambda x: x.interpolate(limit_direction='both'))
            .fillna(median))

print (df)
   ID  x     y     z
0   1  0  12.0  36.0
1   1  1  12.0  37.0
2   1  2  11.5  38.0
3   1  3  11.0  37.0
4   2  0  11.5  37.0
5   2  1  11.5  37.0
6   2  2  11.5  37.0
7   2  3  11.5  37.0