DataWhale & Pandas(文本数据)
学习大纲:
import numpy as np
import pandas as pd
一、str对象
var = 'abcd'
str.upper(var) # Python内置str模块
# 'ABCD'
s = pd.Series(['abcd', 'efg', 'hi'])
s.str.upper() # pandas中str对象上的upper方法
# 0 ABCD
# 1 EFG
# 2 HI
# dtype: object
#通过 [] 可以取出某个位置的元素
var[0]
# 'a'
# 通过切片得到子串
var[-1: 0: -2]
# 'db'
# 通过对 str 对象使用 [] 索引器,可以完成完全一致的功能,并且如果超出范围则返回缺失值
s.str[0]
s.str[-1: 0: -2]
s.str[2]
# 0 c
# 1 g
# 2 NaN
# dtype: object
二、正则表达式基础
参考这个项目 learn-regex-zh
2.1 元字符基础
元字符 |
描述 |
---|---|
. |
匹配除换行符以外的任意字符 |
[ ] |
字符类,匹配方括号中包含的任意字符。 |
[^ ] |
否定字符类,匹配方括号中不包含的任意字符 |
* |
匹配前面的子表达式零次或多次 |
+ |
匹配前面的子表达式一次或多次 |
? |
匹配前面的子表达式零次或一次 |
{n,m} |
花括号,匹配前面字符至少 n 次,但是不超过 m 次 |
(xyz) |
字符组,按照确切的顺序匹配字符xyz。 |
| |
分支结构,匹配符号之前的字符或后面的字符 |
\ |
转义符,它可以还原元字符原来的含义 |
^ |
匹配行的开始 |
$ |
匹配行的结束 |
2.2 简写字符集
此外,正则表达式中还有一类简写字符集,其等价于一组字符的集合:
简写 |
描述 |
---|---|
\w |
匹配所有字母、数字、下划线: [a-zA-Z0-9_] |
\W |
匹配非字母和数字的字符: [^\w] |
\d |
匹配数字: [0-9] |
\D |
匹配非数字: [^\d] |
\s |
匹配空格符: [\t\n\f\r\p{Z}] |
\S |
匹配非空格符: [^\s] |
\B |
匹配一组非空字符开头或结尾的位置,不代表具体字符 |
Ex1:房屋信息数据集
现有一份房屋信息数据集如下:
df = pd.read_excel('./data/house_info.xls', usecols=[ 'floor','year','area','price']) df.head(3)
floor year area price 0 高层(共6层) 1986年建 58.23㎡ 155万1 中层(共20层) 2020年建 88㎡ 155万2 低层(共28层) 2010年建 89.33㎡ 365万
- 将
year
列改为整数年份存储。df.year = pd.to_numeric(df.year.str[:4])) # 取前四列 df.head(3)
- 将
floor
列替换为Level, Highest
两列,其中的元素分别为string
类型的层类别(高层、中层、低层)与整数类型的最高层数。pat = '(?P<Level>^\w+)\D+(?P<Highest>\d+)\D+$' #正则表达式 df = pd.concat([df.floor.str.extract(pat), df.drop(columns='floor')], 1) #查重再拼接分组 df.head(3)
- 计算房屋每平米的均价
avg_price
,以***元/平米
的格式存储到表中,其中***
为整数。avg_price=(pd.to_numeric(df.price.str[:-1])/pd.to_numeric( df.area.str[:-1])*1e4)) df['avg_price'] = avg_price.astype('string')+'元/平米' #以***元/平米的格式存储到表 avg_price.head(3)
Ex2:《权力的游戏》剧本数据集
现有一份权力的游戏剧本数据集如下:
df = pd.read_csv('../data/script.csv')
df.head(3)
Release Date | Season | Episode | Episode Title | Name | Sentence | |
---|---|---|---|---|---|---|
0 | 2011-04-17 | Season 1 | Episode 1 | Winter is Coming | waymar royce | What do you expect? They're savages. One lot s... |
1 | 2011-04-17 | Season 1 | Episode 1 | Winter is Coming | will | I've never seen wildlings do a thing like this... |
2 | 2011-04-17 | Season 1 | Episode 1 | Winter is Coming | waymar royce | How close did you get? |
- 计算每一个
Episode
的台词条数。df.columns = df.columns.str.strip() #出去空格 df.groupby(['Season','Episode'])['Sentence'].count().head() #分组统计
- 以空格为单词的分割符号,请求出单句台词平均单词量最多的前五个人。
df.Sentence.str.split().str.len().groupby(df.Name).mean().sort_values().tail() #平均单词量最多的排序方式
- 若某人的台词中含有问号,那么下一个说台词的人即为回答者。若上一人台词中含有 nn 个问号,则认为回答者回答了 nn 个问题,请求出回答最多问题的前五个人。
df.Sentence.str.count('\?').shift().groupby(df.Name).sum().sort_values().tail().astype('int64') #最多升序