将缺失值估算为 0,并在 Pandas 中创建指标列

Impute missing values to 0, and create indicator columns in Pandas

我在 Pandas、

中有一个非常简单的数据框
testdf = [{'name' : 'id1', 'W': np.NaN, 'L':   0, 'D':0},
          {'name' : 'id2', 'W':   0, 'L': np.NaN, 'D':0},
          {'name' : 'id3', 'W':  np.NaN, 'L':  10, 'D':0},
          {'name' : 'id4', 'W':  75, 'L':  20, 'D':0}
          ]
testdf = pd.DataFrame(testdf)
testdf = testdf[['name', 'W', 'L', 'D']]  

看起来像这样:

| name | W   | L   | D |
|------|-----|-----|---|
| id1  | NaN | 0   | 0 |
| id2  | 0   | NaN | 0 |
| id3  | NaN | 10  | 0 |
| id4  | 75  | 20  | 0 |

我的目标很简单:
1) 我想通过简单地用 0.
替换它们来估算所有缺失值 2) 接下来,我想创建带有 0 或 1 的指示符列,以指示新值(0)确实是由插补过程创建的。

直接展示而不是用文字解释可能更容易:

| name | W  | W_indicator | L  | L_indicator | D | D_indicator |
|------|----|-------------|----|-------------|---|-------------|
| id1  | 0  | 1           | 0  | 0           | 0 | 0           |
| id2  | 0  | 0           | 0  | 1           | 0 | 0           |
| id3  | 0  | 1           | 10 | 0           | 0 | 0           |
| id4  | 75 | 0           | 20 | 0           | 0 | 0           |

我的尝试失败了,因为我无法尝试将所有非 NaN 值更改为某个占位符值,然后将所有 NaN 更改为 0,然后将占位符值改回 NaN,等等。它变得混乱很快。然后我不断收到各种切片警告。面具都弄乱了。我敢肯定,有比我古怪的启发式方法更优雅的方法来做到这一点。

您可以使用 isnull with convert to int by astype and add_prefix for new df and then concat with reindex_axis by cols created by some solution from :

cols = ['W','L','D']
df = testdf[cols].isnull().astype(int).add_suffix('_indicator')
print (df)
   W_indicator  L_indicator  D_indicator
0            1            0            0
1            0            1            0
2            1            0            0
3            0            0            0

的解决方案:

def mygen(lst):
    for item in lst:
        yield item
        yield item + '_indicator'

df1 = pd.concat([testdf.fillna(0), df], axis=1) \
        .reindex_axis(['name'] + list(mygen(cols)), axis=1)
print (df1)

  name     W  W_indicator     L  L_indicator  D  D_indicator
0  id1   0.0            1   0.0            0  0            0
1  id2   0.0            0   0.0            1  0            0
2  id3   0.0            1  10.0            0  0            0
3  id4  75.0            0  20.0            0  0            0

的解决方案:

cols = ['name'] + [item for x in cols for item in (x, x + '_indicator')]
df1 = pd.concat([testdf.fillna(0), df], axis=1).reindex_axis(cols, axis=1)
print (df1)
  name     W  W_indicator     L  L_indicator  D  D_indicator
0  id1   0.0            1   0.0            0  0            0
1  id2   0.0            0   0.0            1  0            0
2  id3   0.0            1  10.0            0  0            0
3  id4  75.0            0  20.0            0  0            0

聚会晚了几年,但我是这样做的:

transformer = FeatureUnion(
     transformer_list=[
         ('features', SimpleImputer(strategy='mean')),
         ('indicators', MissingIndicator())])
transformer = transformer.fit(Xnum, df.fraud)
results = transformer.transform(Xnum)
results.shape