pd.Series 替换第一次出现的地方
pd.Series replace first occurrence
当尝试用 np.NaN 替换系列的最小值时,我得到了 "multiple" 替换。
我曾尝试使用 series.replace 方法,但它会导致替换所有出现的最小值。
举个例子:
series = pd.Series([0,0,1,1])
#when calling the replace:
series = series.apply(lambda x: x.replace(min(x),np.NaN))
#the output is:
0 NaN
1 NaN
2 1
3 1
#and the desired output is:
0 NaN
1 0
2 1
3 1
所以基本上,我怎样才能只替换第一次出现的重复最小值?
loc
+idxmin
idxmin
returns 序列中第一次出现最小值的索引。
sss.loc[sss.idxmin()] = np.nan
您可以使用 np.where
并添加第二个条件以获得第一个重复值 return True with duplcated
.
s = pd.Series([0,0,1,1,4])
s = np.where(s.duplicated(keep='last') & s.eq(s.min()), np.nan, s)
s
Out[1]: array([nan, 0., 1., 1., 4.])
与使用 idxmin
.
不同,如果不重复,此方法将不会替换您的 min
s = pd.Series([0,1,1,3,4,4])
s = np.where(s.duplicated(keep='last') & s.eq(s.min()), np.nan, s)
s
Out[1]: array([0., 1., 1., 3., 4., 4.])
当尝试用 np.NaN 替换系列的最小值时,我得到了 "multiple" 替换。
我曾尝试使用 series.replace 方法,但它会导致替换所有出现的最小值。
举个例子:
series = pd.Series([0,0,1,1])
#when calling the replace:
series = series.apply(lambda x: x.replace(min(x),np.NaN))
#the output is:
0 NaN
1 NaN
2 1
3 1
#and the desired output is:
0 NaN
1 0
2 1
3 1
所以基本上,我怎样才能只替换第一次出现的重复最小值?
loc
+idxmin
idxmin
returns 序列中第一次出现最小值的索引。
sss.loc[sss.idxmin()] = np.nan
您可以使用 np.where
并添加第二个条件以获得第一个重复值 return True with duplcated
.
s = pd.Series([0,0,1,1,4])
s = np.where(s.duplicated(keep='last') & s.eq(s.min()), np.nan, s)
s
Out[1]: array([nan, 0., 1., 1., 4.])
与使用 idxmin
.
s = pd.Series([0,1,1,3,4,4])
s = np.where(s.duplicated(keep='last') & s.eq(s.min()), np.nan, s)
s
Out[1]: array([0., 1., 1., 3., 4., 4.])