数据转换
删除重复元素
DataFrame对象的duplicated()函数可用来检测重复的行,返回元素为布尔型的Series对象。 每个元素对
应一行,如果该行与其他行重复(也就是说该行不是第一次出现),则元素为True; 如果跟前面不重复,则元
素就为False。
返回元素为布尔值的Series对象用处很大,特别适用于过滤操作。通常,所有重复的行都需要从DataFrame
对象中删除。pandas库的drop_duplicates()函数实现了删除功能,该函数返回的是删除重复行后的DataFmme对
象。
 1 dframe = pd.DataFrame({ ‘color‘: [‘white‘,‘white‘,‘red‘,‘red‘,‘white‘],‘value‘: [2,1,3,3,2]})
 2 print(dframe)
 3 print(dframe.duplicated())
 4 # 返回元素为布尔值的Series对象用处很大,特别适用于过滤操作。
 5 print( dframe[dframe.duplicated()])
 6 print(dframe.drop_duplicates())
 7 输出:
 8    color  value
 9 0  white      2
10 1  white      1
11 2    red      3
12 3    red      3
13 4  white      2
14 0    False
15 1    False
16 2    False
17 3     True
18 4     True
19 dtype: bool
20    color  value
21 3    red      3
22 4  white      2
23    color  value
24 0  white      2
25 1  white      1
26 2    red      3
用映射替换元素
要用新元素替换不正确的元素,需要定义一组映射关系。在映射关系中,旧元素作为键,新元素作为值。
DataFrame对象中两种旧颜色被替换为正确的元素。还有一种常见情况,是把NaN替换为其他值,比如0。
这种情况下,仍然可以用replace()函数,它能优雅地完成该项操作。
 1 frame8 = pd.DataFrame({
 2     ‘item‘: [‘ball‘, ‘mug‘, ‘pen‘, ‘pencil‘, ‘ashtray‘],
 3     ‘color‘: [‘white‘, ‘rosso‘, ‘verde‘, ‘black‘, ‘yellow‘],
 4     ‘price‘: [5.56, 4.20, 1.30, 0.56, 2.75]
 5 })
 6 print(frame8)
 7 newcolors = {
 8     ‘rosso‘: ‘red‘,
 9     ‘verde‘: ‘green‘
10 }
11 print(frame8.replace(newcolors))
12 
13 ser = pd.Series([13, np.nan, 4, 6, np.nan, 3])
14 print(ser.replace(np.nan, 0))
输出结果:
  
用映射添加元素
下面只是部分功能的展示,详情请参考官方文档。
 1 frame9  = pd.DataFrame({
 2     ‘item‘:[‘ball‘,‘mug‘,‘pen‘,‘pencil‘,‘ashtray‘],
 3     ‘color‘:[‘white‘,‘red‘,‘green‘,‘black‘,‘yellow‘]
 4 })
 5 print(frame9)
 6 price = {
 7     ‘ball‘ : 5.56,
 8     ‘mug‘ : 4.20,
 9     ‘bottle1‘ : 1.30,
10     ‘scissors‘ : 3.41,
11     ‘pen‘ : 1.30,
12     ‘pencil‘ : 0.56,
13     ‘ashtray‘ : 2.75
14 }
15 frame9[‘price‘] = frame9[‘item‘].map(price)  # 这里是按‘item’的对应关系添加
16 print(frame9)
输出结果:
  
官方文档案例:
1 df = pd.DataFrame({
2     ‘A‘: [‘bat‘, ‘foo‘, ‘ibat‘],
3     ‘B‘: [‘abc‘, ‘bar‘, ‘xyz‘]
4 })
5 # r‘^ba.$‘是匹配最后三个字符中前面量为ba的;$匹配结尾的
6 print(df.replace(to_replace=r‘^ba.$‘, value=‘new‘, regex=True))
输出结果:(上面关于正则的知识点请点击参考博客)
  
重命名轴索引
Python数据分析库pandas ------ pandas
原文:https://www.cnblogs.com/dan-baishucaizi/p/9413165.html