我在 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通过 astype 转换为 int和 add_prefix对于新的 df 然后是 concat与 reindex_axis由 this answers 中的一些解决方案创建的 cols :
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
解决方案 generator :
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
解决方案 list comprehenion :
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
