pandas中的数据去重和替换(duplicated、drop_

2019-03-30  本文已影响0人  越大大雨天
s = pd.Series([1,1,1,1,2,2,2,3,4,5,5,5,5])
print(s.duplicated())
#duplicated()得到重复值判断的布尔值,再选择布尔值为False的既为非重复值
print(s[s.duplicated()==False])
#或者直接采用drop_duplicates()去除重复值,返回唯一值
print(s.drop_duplicates())

输出:



0     False
1      True
2      True
3      True
4     False
5      True
6      True
7     False
8     False
9     False
10     True
11     True
12     True
dtype: bool
0    1
4    2
7    3
8    4
9    5
dtype: int64
0    1
4    2
7    3
8    4
9    5
dtype: int64

最后两个输出结果相同,不过只是去重的话,当然选择drop_duplicates()方法更方便呀。
针对DataFrame数据,只需选择某列操作即可,即:df["column"].drop_duplicates()

s = pd.Series(list('ascaazsd'))
print(s.replace('a', np.nan))
print(s.replace(['a','s'] ,np.nan))
print(s.replace({'a':'hello world!','s':123}))
# 可一次性替换一个值或多个值
# 可传入列表或字典

输出:

0    NaN
1      s
2      c
3    NaN
4    NaN
5      z
6      s
7      d
dtype: object
0    NaN
1    NaN
2      c
3    NaN
4    NaN
5      z
6    NaN
7      d
dtype: object
0    hello world!
1             123
2               c
3    hello world!
4    hello world!
5               z
6             123
7               d
dtype: object

上一篇 下一篇

猜你喜欢

热点阅读