2017-07-15 50 views
2

创建指标列我有熊猫一个非常简单的数据帧,它看起来像这样填充缺失值设置为0,并在熊猫

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等等等等。它太杂乱了。然后我不断收到各种切片警告。面具变得杂乱无章。我敢肯定,比起我那些不可靠的启发式方法,有更好的方法来做到这一点。

+0

如果我的回答很有帮助,别忘了接受它。谢谢。 (也可以检查链接的问题和很好的答案,并把它们加起来) – jezrael

+0

是的先生我在上面 –

回答

1

您可以通过astypeadd_prefixdf由一些解决方案中创建colsthis answers使用isnull与转换为int,然后concatreindex_axis

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