第八章 文本数据
学习参考:http://datawhale.club/t/topic/579
Ex1:房屋信息数据集
现有一份房屋信息数据集如下:
import numpy as np
import pandas as pd
df = pd.read_excel('../data/house_info.xls', usecols=['floor','year','area','price'])
df.head(3)
- 将
year
列改为整数年份存储。 - 将
floor
列替换为Level, Highest
两列,其中的元素分别为string
类型的层类别(高层、中层、低层)与整数类型的最高层数。 - 计算房屋每平米的均价
avg_price
,以***元/平米
的格式存储到表中,其中***
为整数。
#1.将year列改为整数年份存储
df.isna().sum()/df.shape[0] # 各列的缺失信息
year = df['year'].str.rstrip("年建")
year = pd.to_numeric(year, errors='coerce').astype("Int64") # df中包含缺失值
df['year'] = year
df.head()
#2.将floor列替换为Level, Highest两列,其中的元素分别为string类型的层类别(高层、中层、低层)与整数类型的最高层数。
pat = '(?P<level>\w?层)(共(?P<Highest>\d+)层)'
df1 = df['floor'].str.extract(pat)
df1['level'] = df1['level'].astype("string")
df1['Highest']= pd.to_numeric(df1['Highest'], errors='coerce').astype("Int64")
df = pd.concat([df,df1],1)
df = df.loc[:,'year':]
#另外的方法:df = df.drop(columns=['floor'])
df.head()
#3.计算房屋每平米的均价avg_price,以***元/平米的格式存储到表中,其中***为整数。
df1 = df.copy()
df1['area'] = pd.to_numeric(df1['area'].str[:-1], errors='coerce').astype("float64")
df1['price'] = pd.to_numeric(df1['price'].str[:-1], errors='coerce').astype("float64")
df1.head()
df["avg_price"] = ((10000*df1['price']/df1['area']).astype('int')).astype("string")+"元/平米"
df.head()
Ex2:《权力的游戏》剧本数据集
现有一份权力的游戏剧本数据集如下:
df = pd.read_csv('../data/script.csv')
df.head(3)
- 计算每一个
Episode
的台词条数。 - 以空格为单词的分割符号,请求出单句台词平均单词量最多的前五个人。
- 若某人的台词中含有问号,那么下一个说台词的人即为回答者。若上一人台词中含有 n n n个问号,则认为回答者回答了 n n n个问题,请求出回答最多问题的前五个人。
#1.计算每一个Episode的台词条数
df.columns = df.columns.str.strip() # 列名包含左右边空格,需要去除掉
df.groupby(['Season','Episode'])['Sentence'].count()
#2.以空格为单词的分割符号,请求出单句台词平均单词量最多的前五个人。
df['word_count'] = df['Sentence'].str.count('\s')+1 # 句子空格数目+1 = 句子单词数
actor_word = df.groupby(['Name'])['word_count'].mean().reset_index().sort_values('word_count', ascending=False)
actor_word.head(5)
#3.若某人的台词中含有问号,那么下一个说台词的人即为回答者。若上一人台词中含有 𝑛 个问号,则认为回答者回答了 𝑛 个问题,请求出回答最多问题的前五个人。
df1 = df.copy()
df1['question_count'] = df1['Sentence'].str.count('\?') # 提问者台词中的'?'的数量
answer_list = df1['question_count'][:-1].tolist()
answer_list.insert(0,0) # 回答者回答问题的数量(第一个演员默认回答数量为0),实际上长列表插入值的方式效率不高
df1['answer_count'] = answer_list
answer_df = df1.groupby(['Name'])['answer_count'].sum().reset_index().sort_values('answer_count', ascending=False)
answer_df.head(5)
答案提供了另一种思路:
s = pd.Series(df.Sentence.values, index=df.Name.shift(-1)) # periods = -1(默认为1),将Name列向上移动一位,最后一位用NaN填充
s
s.str.count('\?').groupby('Name').sum().sort_values(ascending=False).head()