在Pandas中的列之间替换重复值

时间:2016-10-06 23:49:43

标签: python pandas

我有一个简单的数据框:

df = [    {'col1' : 'A', 'col2': 'B', 'col3':   'C', 'col4':'0'},
          {'col1' : 'M', 'col2':   '0', 'col3': 'M', 'col4':'0'},
          {'col1' : 'B', 'col2':  'B', 'col3':  '0', 'col4':'B'},
          {'col1' : 'X', 'col2':  '0', 'col3':  'Y', 'col4':'0'}
          ]
df = pd.DataFrame(df)
df = df[['col1', 'col2', 'col3', 'col4']]
df  

看起来像这样:

| col1 | col2 | col3 | col4 |
|------|------|------|------|
| A    | B    | C    | 0    |
| M    | 0    | M    | 0    |
| B    | B    | 0    | B    |
| X    | 0    | Y    | 0    |

我只想用行中的字符' 0'替换重复的字符。它归结为保持我们遇到的第一个重复值,如下所示:

| col1 | col2 | col3 | col4 |
|------|------|------|------|
| A    | B    | C    | 0    |
| M    | 0    | 0    | 0    |
| B    | 0    | 0    | 0    |
| X    | 0    | Y    | 0    |

这看起来很简单,但我被卡住了。任何朝着正确方向的推动都会非常感激。

1 个答案:

答案 0 :(得分:10)

您可以使用<link rel="import" href="../bower_components/polymer/polymer.html" /> <dom-module id="poem-element"> <template> <div></div> <div id="poems"></div> </template> <script> Polymer({ is: "poem-element", ready: function() { var newArray = ["poem1", "poem2", "poem3"]; var random = (Math.ceil(Math.random() * 4) - 1); this.querySelector("#poems").innerHTML= poems[randomPoem]; } }) </script> </dom-module> 方法返回元素是否重复的布尔索引器:

duplicated

然后,您可以通过将数据映射到数据框的各行来创建掩码,并使用In [214]: pd.Series(['M', '0', 'M', '0']).duplicated() Out[214]: 0 False 1 False 2 True 3 True dtype: bool 执行替换:

where
相关问题