Pandas有两种排序方式,它们分别是:
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
# 按标签排序
sorted_df=unsorted_df.sort_index()
# 排序顺序desc
unsorted_df.sort_index(ascending=False)
# 按列排列
unsorted_df.sort_index(axis=1)
# 按值排序
unsorted_df.sort_values(by='col1')
# 按值排序(两列)
unsorted_df.sort_values(by=['col1','col2'])
sort_values()提供了从mergeesort,heapsort和quicksort中选择算法的一个配置。Mergesort是唯一稳定的算法
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})
sorted_df = unsorted_df.sort_values(by='col1' ,kind='mergesort')
print (sorted_df)
Pandas提供了一组字符串的操作 这些方法几乎都是使用到的是Python字符串函数 需要将Series对象转化为String对象来操作
举例:
import pandas as pd
import numpy as np
s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
print (s.str.lower())
s.str.lower() 先转换为str,然后进行操作
字符串常用处理函数:
NO. | 函数 | details |
---|---|---|
1 | lower() | 将Series/Index中的字符串转换为小写 |
2 | upper() | 将Series/Index中的字符串转换为大写 |
3 | len() | 计算字符串长度 |
4 | strip() | 帮助从两侧的系列/索引中的每个字符串中删除空格(包括换行符) |
5 | split(' ') | 用给定的模式拆分每个字符串 |
6 | cat(sep=' ') | 使用给定的分隔符连接系列/索引元素 |
7 | get_dummies() | 返回具有单热编码值的数据帧(DataFrame) |
8 | contains(pattern) | 如果元素中包含子字符串,则返回每个元素的布尔值True,否则为False |
9 | replace(a,b) | 将值a替换为值b |
10 | repeat(value) | 重复每个元素指定的次数 |
11 | count(pattern) | 返回模式中每个元素的出现总数 |
12 | startswith(pattern) | 如果系列/索引中的元素以模式开始,则返回true |
13 | endswith(pattern) | 如果系列/索引中的元素以模式结束,则返回true |
14 | find(pattern) | 返回模式第一次出现的位置 |
15 | findall(pattern) | 返回模式的所有出现的列表 |
16 | swapcase | 变换字母大小写 |
17 | islower() | 检查系列/索引中每个字符串中的所有字符是否小写,返回布尔值 |
18 | isupper() | 检查系列/索引中每个字符串中的所有字符是否大写,返回布尔值 |
19 | isnumeric() | 检查系列/索引中每个字符串中的所有字符是否为数字,返回布尔值 |
字符串处理函数在大家的不断练习和使用中会起到巨大的作用,可快速处理绝大多数的字符串处理场景!
作者:Johngo
配图:Pexels