在多列中用np.nan替换各种重复的值

时间:2019-04-24 02:26:43

标签: python pandas replace duplicates

我正在尝试在replace duplicate中的多个columnspandas df个值。对于下面的df,我有相应的日期和值。每个日期的所有值均相同。我只想保留每个日期的第一个值,并用duplicate替换以下np.nan值。以下是我的尝试:

import pandas as pd
import numpy as np

d = ({
    'Date' : ['1/1/18','1/1/18','1/1/18','2/1/18','2/1/18','3/2/18','3/2/18','3/2/18'],                 
    'Val_D' : [10,10,10,22,22,10,10,10],      
    'Val_M' : [100,100,100,100,100,240,240,240],                                   
     })

df = pd.DataFrame(data = d)

df['Date'] = pd.to_datetime(df['Date'], format= '%d/%m/%y')

pd.Series([10,22,100,240]).duplicated()
dup = df.apply(pd.Series.duplicated, axis = 1)
df = df.where(~dup,np.nan)

print(df)

预期输出:

     Date Val_D Val_M
0  1/1/18    10   100
1  1/1/18            
2  1/1/18            
3  2/1/18    22      
4  2/1/18            
5  3/2/18    10   240
6  3/2/18            
7  3/2/18

2 个答案:

答案 0 :(得分:2)

好吧,一种方法是简单地使用diff + ne

s = df[['Val_D', 'Val_M']]
df[['Val_D', 'Val_M']] = s[s.diff().ne(0)].fillna('')

即使这会产生预期的输出,列的dtypes也会变成object,并且您会失去数字的矢量化能力。因此,我建议您不要这样做。没有最后一个fillna(''),您将获得

    Date        Val_D   Val_M
0   2018-01-01  10.0    100.0
1   2018-01-01  NaN     NaN
2   2018-01-01  NaN     NaN
3   2018-01-02  22.0    NaN
4   2018-01-02  NaN     NaN
5   2018-02-03  10.0    240.0
6   2018-02-03  NaN     NaN
7   2018-02-03  NaN     NaN

dtypesfloat。现在,有了fillna('')件,您就可以

    Date        Val_D   Val_M
0   2018-01-01  10      100
1   2018-01-01      
2   2018-01-01      
3   2018-01-02  22  
4   2018-01-02      
5   2018-02-03  10      240
6   2018-02-03      
7   2018-02-03      

具有object dtypes。

答案 1 :(得分:1)

我将wherediff一起使用

df[['Val_D', 'Val_M']].where(df[['Val_D', 'Val_M']].diff().ne(0))
Out[1136]: 
   Val_D  Val_M
0   10.0  100.0
1    NaN    NaN
2    NaN    NaN
3   22.0    NaN
4    NaN    NaN
5   10.0  240.0
6    NaN    NaN
7    NaN    NaN
df[['Val_D', 'Val_M']]= df[['Val_D', 'Val_M']].where(df[['Val_D', 'Val_M']].diff().ne(0))