T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 75 天:Plotly 交互图表:安卓应用商店分析

这是「Python 100 天」系列第 75 天的学习笔记:Plotly 交互图表:安卓应用商店分析。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

一万多条 Google Play 应用数据(分类、评分、安装量、价格、类型),要回答:免费还是付费多?哪个分类最多?哪个分类安装量最大?付费应用能赚多少?哪个分类的付费应用最贵?

README 知识点:去 NaN 与去重、饼图与环形图、用 .stack() 拆嵌套字段、Plotly 的分组柱状图与箱线图。

一、清洗四步

1
2
3
4
5
df_apps.drop(['Last_Updated', 'Android_Ver'], axis=1, inplace=True)   # 删无用列
nan_rows = df_apps[df_apps.Rating.isna()] # 先看再删
df_apps_clean = df_apps.dropna() # 删空值行
duplicated_rows = df_apps_clean[df_apps_clean.duplicated()] # 先看重复
df_apps_clean = df_apps_clean.drop_duplicates(subset=['App', 'Type', 'Price'])

"先看再删"是纪律:print(nan_rows.shape) 告诉你删掉了多少;df[df.App=='Instagram'] 让你看到同一个 App 有免费版和付费版两条记录——所以去重不能只按 App,要按 (App, Type, Price) 组合。

只按 App 去重会把"免费版+付费版"砍成一条,数据就错了。subset 选错比不去重更危险。

二、把带符号的字符串转成数字

1
2
3
4
5
df_apps_clean.Installs = df_apps_clean.Installs.astype(str).str.replace(',', "")
df_apps_clean.Installs = pd.to_numeric(df_apps_clean.Installs)

df_apps_clean.Price = df_apps_clean.Price.astype(str).str.replace('$', "")
df_apps_clean.Price = pd.to_numeric(df_apps_clean.Price)

"10,000+"、"$4.99" 这种字段在 CSV 里是字符串,describe() 和 sum() 全都没法用(info() 会显示 object)。必须先去掉逗号和美元符,再 to_numeric。

注意 "10,000+" 里的 + 会被 to_numeric(errors='coerce') 变成 NaN——这份数据的处理方式说明它先把 + 处理掉了或数据里没有。

三、派生列:估算营收

1
df_apps_clean['Revenue_Estimate'] = df_apps_clean.Installs.mul(df_apps_clean.Price)

Series.mul() 就是逐元素相乘(等价 Installs * Price)。安装量 × 价格 = 粗略营收,虽然忽略了内购和退款,但足够做量级对比。

前面还有一步 df_apps_clean = df_apps_clean[df_apps_clean['Price'] < 250]:去掉极端值(比如某个"咨询类"应用标价 400 美元),否则均值和中位数全被带偏。

四、Plotly 和 Matplotlib 的区别

Matplotlib Plotly
输出静态图片可交互 HTML(悬停看数值、缩放、图例点击隐藏)
语法plt.xxx 状态机px.xxx(data, x=, y=) 声明式
适合论文、报告插图网页、探索、演示
1
2
3
import plotly.express as px
fig = px.bar(x=..., y=...)
fig.show() # notebook 里内嵌,浏览器里可交互

fig.show() 不是 plt.show(),两套 API 不能混。

五、饼图 → 环形图

1
2
fig = px.pie(labels=ratings.index, values=ratings.values, names=ratings.index, hole=0.6)
fig.update_traces(textposition='inside', textfont_size=15, textinfo='percent')

hole=0.6 把饼挖空成环形(donut)。textinfo='percent+label' 控制显示什么(percent/label/value 可组合)。环形图比饼图好在中间空白可以放总数。

六、.stack() 拆多值字段

1
2
stack = df_apps_clean.Genres.str.split(';', expand=True).stack()
num_genres = stack.value_counts()

Genres 一格里可能是 "Action;Adventure":

  1. str.split(';', expand=True) → 拆成多列;
  2. .stack() → 多列压成一列(长表);
  3. value_counts() → 每个类型出现几次。

这是处理"一格多值"的标准套路(也叫 explode)。pandas 0.25 之后还可以直接 df.explode('Genres')。

七、分组柱状图与箱线图

1
2
3
g_bar = px.bar(df, x='Category', y='App', color='Type', barmode='group')

box = px.box(df_paid_apps, x='Category', y='Price', points='all', notched=True)
  • barmode='group':同一分类下免费/付费并排(对比用);'stack' 是堆叠(看总量构成);
  • yaxis=dict(type='log'):对数轴,否则几十万和几十的柱子差太远,小的看不见;
  • 箱线图:一条线看懂中位数、四分位、离群值,比均值更能反映分布(points='all' 把每个点都画出来)。

代码全文(notebook 全部单元格)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# plotly.express as px:高层绘图 API,一行出交互图(可缩放/悬停)。
# 与 matplotlib 的静态图不同,px 返回 Figure 对象,用 fig.show() 在浏览器渲染。
import pandas as pd
import plotly.express as px

# 设置浮点显示格式,后面算收入估算时不会被一长串小数淹没。
# Show numeric output in decimal format e.g., 2.15
pd.options.display.float_format = '{:,.2f}'.format

# 读应用商店数据(Google Play 抓取):App/Category/Rating/Reviews/Size/Installs/Type/Price/Content_Rating/Genres。
df_apps = pd.read_csv('apps.csv')

# shape:先知道有多少行多少列(约 1 万行)。
df_apps.shape

# head():看真实数据长什么样。
df_apps.head()

# sample(5):随机抽 5 行 —— 比 head 更能代表整体,能发现排序带来的偏差。
df_apps.sample(5)

# drop([...], axis=1, inplace=True):按列名删列(axis=1 表示列),原地修改。
# 删掉用不上的 Last_Updated 和 Android_Ver。
df_apps.drop(['Last_Updated', 'Android_Ver'], axis=1, inplace=True)
df_apps.head()

# 布尔索引筛出 Rating 为空的行,先看有多少、长什么样,再决定删还是填。
nan_rows = df_apps[df_apps.Rating.isna()]
print(nan_rows.shape)
nan_rows.head()

# dropna():删掉任何含缺失的行(默认 how='any'),返回新表 —— 所以必须重新赋值。
# 删完再看 shape,对比少了多少行。
df_apps_clean = df_apps.dropna()
df_apps_clean.shape

# DataFrame.duplicated():判断每行是否与前面某行完全重复,返回布尔序列;
# 再用它做布尔索引,把重复行全部列出来。
duplicated_rows = df_apps_clean[df_apps_clean.duplicated()]
print(duplicated_rows.shape)
duplicated_rows.head()

# 看 Instagram 出现几次 —— 同款应用不同版本/不同抓取时间造成的重复。
df_apps_clean[df_apps_clean.App == 'Instagram']

# drop_duplicates():去掉完全重复的行(保留第一条),返回新表。
df_apps_clean = df_apps_clean.drop_duplicates()

# 再看 Instagram:全列相同的那些没了,但仍有重复 —— 说明有些行只有个别列不同。
df_apps_clean[df_apps_clean.App == 'Instagram']

# drop_duplicates(subset=['App','Type','Price']):只按这三列判断重复,
# 业务含义是“同一个应用的同一种付费类型只保留一条”。subset 是关键参数。
# need to specify the subset for indentifying duplicates
df_apps_clean = df_apps_clean.drop_duplicates(subset=['App', 'Type', 'Price'])
df_apps_clean[df_apps_clean.App == 'Instagram']

# 清洗完的规模。
df_apps_clean.shape

# 按评分降序:评分最高的应用(注意评分高不代表下载多)。
df_apps_clean.sort_values('Rating', ascending=False).head()

# 按体积降序:最大的应用。
df_apps_clean.sort_values('Size_MBs', ascending=False).head()

# 评论数最多的 50 个 —— head(50) 一次看一屏,确认头部应用。
df_apps_clean.sort_values('Reviews', ascending=False).head(50)

# Content_Rating 的分布(Everyone / Teen / Mature…),value_counts 默认降序。
ratings = df_apps_clean.Content_Rating.value_counts()
ratings

# px.pie(labels=, values=):饼图。labels 是分类名,values 是对应数量。
# 注意:新版 plotly 用 names= 取代 labels=,两者都传会告警。
fig = px.pie(labels=ratings.index, values=ratings.values)

fig.show()

# 加标题 + update_traces 控制标签样式:
# textposition='outside' 标签放饼外(饼内放不下时用);
# textinfo='percent+label' 显示“百分比+名称”。
fig = px.pie(labels=ratings.index,
values=ratings.values,
title="Content Rating",
names=ratings.index,
)
fig.update_traces(textposition='outside', textinfo='percent+label')

fig.show()

# hole=0.6:把饼图挖空成环形图(甜甜圈),中间可放总计;
# textinfo 改成 'percent' 并放大字号,视觉更干净。
fig = px.pie(labels=ratings.index,
values=ratings.values,
title="Content Rating",
names=ratings.index,
hole=0.6, # makes a donut chart =)
)
fig.update_traces(textposition='inside', textfont_size=15, textinfo='percent')

fig.show()

# Installs.describe():注意结果是 object 类型 —— 因为它带逗号('10,000+'),被当成字符串。
df_apps_clean.Installs.describe()

# info():每列的非空数量与 dtype,用来定位“数字被读成字符串”的列。
df_apps_clean.info()

# groupby('Installs').count():把每个“安装量字符串”当成一个类别来数,
# 能直观看到 '1,000+'、'10,000+' 这类分档写法。
# Installs of data type object because of the comma (,) character
df_apps_clean[['App', 'Installs']].groupby('Installs').count()

# 两步转数值:
# astype(str) 先确保是字符串(防止已经是数字时 .str 报错);
# .str.replace(',', '') 去掉千分位逗号(pandas 2.x 默认 regex=False,逗号按字面替换);
# pd.to_numeric(...) 转成数字;'10,000+' 里的 '+' 需要 errors='coerce' 或先去符号才稳妥。
df_apps_clean.Installs = df_apps_clean.Installs.astype(str).str.replace(',', "")

df_apps_clean.Installs = pd.to_numeric(df_apps_clean.Installs)

df_apps_clean[['App', 'Installs']].groupby('Installs').count()

# Price 同理:去掉美元符号再转数值,然后按价格降序看最贵的应用。
df_apps_clean.Price = df_apps_clean.Price.astype(str).str.replace('$', "")
df_apps_clean.Price = pd.to_numeric(df_apps_clean.Price)

df_apps_clean.sort_values('Price', ascending=False).head(20)

# 价格 < 250 过滤掉极端值(有些“应用”标价上千,会毁掉后续图表尺度)。
# 布尔索引后重新赋值,相当于“就地删行”。
df_apps_clean = df_apps_clean[df_apps_clean['Price'] < 250]
df_apps_clean.sort_values('Price', ascending=False).head(5)

# 估算收入 = 安装量 × 价格。Series.mul(other) 是“逐元素相乘”的方法写法,
# 等价于 df.Installs * df.Price。
# 注意:安装量是分档的('10,000+' 实际可能几十万),所以这只是**数量级估算**。
df_apps_clean['Revenue_Estimate'] = df_apps_clean.Installs.mul(df_apps_clean.Price)
df_apps_clean.sort_values('Revenue_Estimate', ascending=False)[:10]

# Category.nunique():有多少个不同分类。
# Number of different categories
df_apps_clean.Category.nunique()

# value_counts()[:10]:应用数量最多的 10 个分类(注意是“应用个数”,不是下载量)。
# Number of apps per category
top10_category = df_apps_clean.Category.value_counts()[:10]
top10_category

# px.bar(x=, y=):最简柱状图。x 传分类名(Index),y 传数量(values)。
bar = px.bar(
x = top10_category.index, # index = category name
y = top10_category.values)

bar.show()

# 换个口径:按分类统计**总安装量**(热度而非数量)。
# agg({'Installs': pd.Series.sum}) 指定聚合函数,再按安装量升序排(横向条形图习惯从小到大)。
# Group apps by category and then sum the number of installations
category_installs = df_apps_clean.groupby('Category').agg({'Installs': pd.Series.sum})
category_installs.sort_values('Installs', ascending=True, inplace=True)

# orientation='h':横向条形图,分类名长的时候更好读。
# update_layout 用于设置全局布局属性(轴标题、宽高、图例位置等)。
h_bar = px.bar(
x = category_installs.Installs,
y = category_installs.index,
orientation='h',
title='Category Popularity')

h_bar.update_layout(xaxis_title='Number of Downloads', yaxis_title='Category')
h_bar.show()

# 两个口径合到一张表:cat_number(应用个数)与 category_installs(总安装量)
# pd.merge(..., on='Category', how='inner'):内连接,只保留两边都有的分类。
# 结果用来做下一张“分类集中度”散点图:个数少但安装多 = 头部效应强。
# Count the number of apps in each category (similar to what we did above)
cat_number = df_apps_clean.groupby('Category').agg({'App': pd.Series.count})
cat_merged_df = pd.merge(cat_number, category_installs, on='Category', how="inner")
print(f'The dimensions of the DataFrame are: {cat_merged_df.shape}')
cat_merged_df.sort_values('Installs', ascending=False)

# px.scatter(df, x=, y=, size=, hover_name=):气泡图。
# size='App' 让点的大小编码应用个数,hover_name 让鼠标悬停显示分类名。
scatter = px.scatter(cat_merged_df, # data
x='App', # column name
y='Installs',
title='Category Concentration',
size='App',
hover_name=cat_merged_df.index,
color='Installs'
)

scatter.update_layout(xaxis_title="Number of Apps (Lower=More Concentrated)",
yaxis_title="Installs",
yaxis=dict(type='log'))

scatter.show()

# Genres.unique():Genres 列里有多少种不同取值(注意一个应用可能有多个 Genre)。
# Number of Genres?
len(df_apps_clean.Genres.unique())

# 问题:Genres 是 'Action;Adventure' 这种用分号拼起来的字符串,直接 value_counts 会按整串计数。
# Problem: Have multiple categories seperated by ;
df_apps_clean.Genres.value_counts().sort_values(ascending=True)[:5]

# 拆解三步:
# .str.split(';', expand=True):按分号拆成多列(每个应用展开成若干列);
# .stack():把宽表压回一列(多级索引 → Series),每个“应用-类型”占一行;
# .value_counts():统计每个类型的出现次数。
# 这是处理“一行多值”字段的标准套路。
# Split the strings on the semi-colon and then .stack them.
stack = df_apps_clean.Genres.str.split(';', expand=True).stack()
print(f'We now have a single column with shape: {stack.shape}')
num_genres = stack.value_counts()
print(f'Number of genres: {len(num_genres)}')

# 取前 15 个类型画条形图,color 用数量做渐变色,color_continuous_scale 指定配色方案。
bar = px.bar(
x = num_genres.index[:15], # index = category name
y = num_genres.values[:15], # count
title='Top Genres',
hover_name=num_genres.index[:15],
color=num_genres.values[:15],
color_continuous_scale='Agsunset'
)

bar.update_layout(xaxis_title='Genre',
yaxis_title='Number of Apps',
coloraxis_showscale=False)

bar.show()

# Type 分布:Free / Paid / 其他。
df_apps_clean.Type.value_counts()

# groupby([...], as_index=False):按两列分组,as_index=False 让分组键变成普通列而不是索引,
# 这样结果可以直接丢给 plotly(px.bar 要求列名可引用)。
# agg({'App': pd.Series.count}) 数每个“分类 × 类型”组合的应用数。
df_free_vs_paid = df_apps_clean.groupby(["Category", "Type"],
as_index=False).agg({'App': pd.Series.count})
df_free_vs_paid.sort_values('App')

# barmode='group':分组柱状图(同分类下 Free/Paid 并排),对比才直观。
g_bar = px.bar(df_free_vs_paid,
x='Category',
y='App',
title='Free vs Paid Apps by Category',
color='Type',
barmode='group',)

g_bar.update_layout(xaxis_title='Category',
yaxis_title='Number of Apps',
xaxis={'categoryorder':'total descending'},
yaxis=dict(type='log'),
)

g_bar.show()

# px.box:箱线图 —— 中位数、四分位、离群点一次看全。
# notched=True 加缺口(中位数置信区间),points='all' 把每个点都画出来。
box = px.box(df_apps_clean,
y='Installs',
x='Type',
color='Type',
notched=True,
points='all',
title='How Many Downloads are Paid Apps Giving Up?'
)

box.update_layout(yaxis=dict(type='log'))

box.show()

# 只看付费应用,后面分析它们的收入与定价。
df_paid_apps = df_apps_clean[df_apps_clean['Type'] == 'Paid']

# 付费应用按分类的收入估算箱线图:看出“哪些品类能赚钱”。
# 箱体被极值拉扁时,下一格会改用对数轴或过滤。
box = px.box(df_paid_apps,
x='Category',
y='Revenue_Estimate',
title='How Much Can Paid Apps Earn?')

box.update_layout(xaxis_title='Category',
yaxis_title='Paid App Ballpark Revenue',
xaxis={'categoryorder':'min ascending'},
yaxis=dict(type='log'))


box.show()

# 付费应用价格的中位数 —— 定价的典型值。
df_paid_apps.Price.median()

# 各分类的价格箱线图;xaxis={'categoryorder':'max descending'} 按最大值排序,
# 避免分类按字母顺序排得看不出重点。
box = px.box(df_paid_apps,
x='Category',
y="Price",
title='Price per Category')

box.update_layout(xaxis_title='Category',
yaxis_title='Paid App Price',
xaxis={'categoryorder':'max descending'},
yaxis=dict(type='log'))


box.show()

走读与要点

  1. pd.options.display.float_format 只影响显示,不改数据。
  2. df.sample(5) 随机抽 5 行,比 head() 更容易发现脏数据。
  3. ratings = df_apps_clean.Content_Rating.value_counts() → 饼图数据(Everyone 占绝大多数)。
  4. groupby('Category').agg({'Installs': sum}) 再 sort_values(ascending=True) → 横向条形图(orientation='h'),分类名在 y 轴更好读。
  5. 散点图看"集中度":x = 该分类的应用数量,y = 总安装量,size = 应用数。点靠左上 = "少数应用吃下大部分下载"(游戏、通讯)。
  6. 付费应用的箱线图回答"付费应用是不是下载量都很低"——是的,中位数远低于免费。

这份代码的问题

(1) df_apps_clean.Price.median() 单独一格

只是打印一个数,没有 print,在脚本里什么都看不到(notebook 里会自动显示最后一个表达式的值)。写成脚本时要加 print。

(2) 链式赋值

1
df_apps_clean.Installs = df_apps_clean.Installs.astype(str)...

在 pandas 的 copy 语义下有 SettingWithCopyWarning 风险。规范写法 df_apps_clean['Installs'] = ...,并确保 df_apps_clean 是 .copy() 出来的。

(3) Installs 的量级问题

"10,000+" 去掉 + 后变成 10000,但真实可能是 50000。这类"下限值"当精确值用,会系统性低估。严谨做法是标注 Installs_is_lower_bound。

(4) hover_name=cat_merged_df.index

散点图想显示分类名,但 merge 之后 index 是 0,1,2…,不是分类名。应该 cat_merged_df.reset_index() 后用 hover_name='Category'。这是图上悬停显示数字而不是名字的常见原因。

(5) 对数轴 + 零值

log 轴遇到 0 会警告/丢点(免费应用 Price=0)。箱线图用 log 轴时要先过滤掉 0。

(6) 分类顺序

xaxis={'categoryorder':'total descending'} 让柱子按总量排序——不加的话按字母序,很难看出重点。

运行结果

  • 内容分级:Everyone 约 80%,Teen 约 10%;
  • 分类数量:FAMILY、GAME 最多;
  • 安装量:GAME、COMMUNICATION 最高(横向条形图);
  • 付费 vs 免费:免费应用数量压倒性多,付费应用下载量中位数低一个数量级;
  • 价格:某些分类(如医疗、金融)付费应用单价明显更高。

易错点

  1. drop_duplicates() 不传 subset:默认比较所有列,几乎删不掉东西。
  2. px.pie 只传 labels 不传 values:比例全错。
  3. fig.show() 在纯脚本里没反应:要 fig.write_html('a.html') 或 fig.show(renderer='browser')。
  4. str.replace 忘了 .str:变成对整个 Series 做字符串替换,报错。

动手改

  • 用 df.explode('Genres') 重写 .stack() 那一段。
  • 修好散点图的 hover_name。
  • 只分析 2018 年之后上架的应用(需要 Last_Updated 列,本例已删——试试别删)。
  • 把最重要的两张图 write_html 存下来,嵌进 Obsidian。

源文件逐个讲解

3 个文件:

文件 规模 职责
day75.ipynb79 个单元格(book 里最多)Google Play 应用市场全量分析(含 Plotly 交互图)
apps.csv10841 行 × 12 列2018 年从 Google Play 爬取的 1 万款应用
README.md8 行说明页

apps.csv——12 列的真实结构

1
2
App,Category,Rating,Reviews,Size_MBs,Installs,Type,Price,Content_Rating,Genres,Last_Updated,Android_Ver
Ak Parti Yardım Toplama,SOCIAL,NaN,0,8.7,0,Paid,$13.99,Teen,Social,"July 28, 2017",4.1 and up

十二列各自的「坑」:

列 类型 坑
App字符串有重名/重复行(同一应用多次上架)
Category字符串还能用
Rating有 NaN约 1474 行没有评分
Reviews整数清白
Size_MBs浮点已换算成 MB
Installs字符串"10,000+" 带逗号和加号
TypeFree/Paid清白
Price字符串"$13.99" 带美元符号
Content_Rating分类清白
Genres字符串"Action;Adventure" 分号分隔多值
Last_Updated字符串"July 28, 2017" 美式日期
Android_Ver字符串用不上

这五个「脏字段」(Rating/Installs/Price/Genres/Last_Updated)就是整天的教学主线——每一个都要专门一步清洗。

day75.ipynb(79 个单元格)

(1)plotly.express:交互式图表

1
2
import pandas as pd
import plotly.express as px

为什么换 Plotly? 对比 Matplotlib:

维度 Matplotlib Plotly
输出静态图片可交互(悬停显示数值、缩放、拖拽)
语法命令式(plt.xxx)声明式(px.xxx(df, x=, y=))
导出PNG/SVGHTML(能嵌网页)

px 是 plotly.express 的固定别名——它接受 DataFrame,直接按列名画。

(2)float_format:只改显示

1
pd.options.display.float_format = '{:,.2f}'.format

千分位 + 两位小数——和 Day 71 一样。这只影响打印,不改数据。

(3)读数据 + 看样本

1
2
3
4
df_apps = pd.read_csv('apps.csv')
df_apps.shape
df_apps.head()
df_apps.sample(5)

sample(5) 抽 5 行随机样本——比 head() 更能发现「异常值」(head() 永远是开头那几行,可能格式一致;随机抽样能撞见各种脏数据)。

这是数据探索的实用技巧:head 看格式、sample 看分布、tail 看尾部异常。

(4)删无用列

1
df_apps.drop(['Last_Updated', 'Android_Ver'], axis=1, inplace=True)

axis=1 是「按列删」——axis=0 是删行。

⚠️ 这是 Pandas 最反直觉的参数:axis=1 表示「沿着行的方向操作」= 删列。

(5)删 NaN 评分

1
2
3
4
5
6
nan_rows = df_apps[df_apps.Rating.isna()]
print(nan_rows.shape)
nan_rows.head()

df_apps_clean = df_apps.dropna()
df_apps_clean.shape

先「看有多少」再「删」——这是好习惯:知道删掉了多少数据,才有判断依据。

dropna() 不加参数 = 删掉「任意一列有 NaN」的行——在 Last_Updated/Android_Ver 已经删掉的前提下,只剩 Rating 有 NaN,所以等价于「删没评分的应用」。

如果那两列还在,dropna() 会因为它们的 NaN 误删更多行——先删列再删行,顺序有讲究。

(6)查重 + 删重

1
2
3
4
5
6
7
8
duplicated_rows = df_apps_clean[df_apps_clean.duplicated()]
print(duplicated_rows.shape)
duplicated_rows.head()

df_apps_clean[df_apps_clean.App == 'Instagram']

df_apps_clean = df_apps_clean.drop_duplicates()
df_apps_clean[df_apps_clean.App == 'Instagram']

duplicated() 默认「整行完全相同」才算重复。

但 Instagram 的重复行「不完全相同」(Reviews 数不同、Size 不同)——所以 drop_duplicates() 删不掉它们。

(7)关键一步:subset

1
2
3
4
# need to specify the subset for indentifying duplicates
df_apps_clean = df_apps_clean.drop_duplicates(subset=['App', 'Type', 'Price'])
df_apps_clean[df_apps_clean.App == 'Instagram']
df_apps_clean.shape

subset=['App', 'Type', 'Price']:只要「应用名 + 类型 + 价格」三列相同,就算重复——保留第一条,删掉后面的。

为什么选这三列? 因为「同名同类型同价格」基本可以确定是同一个应用(Reviews 和 Size 是不同时间点的快照,会变)。

这是「业务判断」而非「技术判断」——选哪几列做去重键,取决于你对数据的理解。

注意 subset 里没有 Category——如果同一个应用被归到两个分类,会被误删一个。

(8)评分最高的问题

1
df_apps_clean.sort_values('Rating', ascending=False).head()

紧接着的 markdown 提了个好问题:

「如果只看评分来判断应用质量,会遇到什么问题?」

答案就在数据里:排在前面的可能是「只有 1 个 5 星评价」的应用——评分高但样本极小,不可靠。

所以后面要用 Reviews 做交叉筛选(Installs 和 Reviews 才能反映真实体量)。

(9)最大的应用

1
df_apps_clean.sort_values('Size_MBs', ascending=False).head()

Size_MBs 最大值约 100 MB——这个数字暗示 Play Store 有 100MB 的上传限制(2018 年的规则)。

(10)评论最多的应用

1
df_apps_clean.sort_values('Reviews', ascending=False).head(50)

head(50) 而不是 head()——为了看「前 50 里有没有付费应用」。

(11)饼图 / 环形图

1
2
3
4
5
ratings = df_apps_clean.Content_Rating.value_counts()
ratings

fig = px.pie(labels=ratings.index, values=ratings.values)
fig.show()

value_counts() 得到「每个分级有多少应用」。

px.pie(labels=..., values=...):最简饼图。

但 labels 和 values 是 Plotly 的旧参数——新版推荐 names= 和 values=(代码下一格就用了 names)。

1
2
3
4
5
6
7
8
fig = px.pie(labels=ratings.index, 
values=ratings.values,
title="Content Rating",
names=ratings.index,
)
fig.update_traces(textposition='outside', textinfo='percent+label')

fig.show()

labels 和 names 同时传——这是「从旧 API 迁移到新 API」的中间状态(labels 被忽略,names 生效)。

update_traces(textinfo='percent+label'):扇区上显示「百分比 + 名称」。

1
2
3
4
5
6
7
fig = px.pie(labels=ratings.index, 
values=ratings.values,
title="Content Rating",
names=ratings.index,
hole=0.6, # makes a donut chart =)
)
fig.update_traces(textposition='inside', textfont_size=15, textinfo='percent')

hole=0.6:中间挖掉 60% 的半径——饼图变环形图(donut chart)。

这是「一个参数改变图表类型」的典型。

(12)Installs 转数字:两步

1
2
3
4
5
6
7
df_apps_clean.Installs.describe()
df_apps_clean.info()

df_apps_clean[['App', 'Installs']].groupby('Installs').count()

df_apps_clean.Installs = df_apps_clean.Installs.astype(str).str.replace(',', "")
df_apps_clean.Installs = pd.to_numeric(df_apps_clean.Installs)

四步逻辑:

① describe() 会失败或只给出「object 类型」的统计——Installs 是字符串,数学运算无效。

② info() 揭示 dtype 是 object——注释里写明了原因:# Installs of data type object because of the comma (,) character。

③ .astype(str).str.replace(',', "")

  • .astype(str):先保证是字符串(防止某些行已被推断成数字);
  • .str.replace(',', ""):.str 访问器——对整列做字符串替换。

.str 是 Pandas 的「字符串向量化」入口:df.col.str.upper()、.str.split()、.str.contains() 都走它。

④ pd.to_numeric(...):字符串 → 数字。

⚠️ 但这个转换有 bug:

Installs 的实际值是 "10,000+"(带加号)——replace(',', "") 之后是 "10000+"——pd.to_numeric 遇到 "+" 会抛 ValueError。

所以后面那行 groupby('Installs').count() 能跑(因为还是字符串),但 to_numeric 会失败——除非这个数据集的 Installs 恰好没有加号(这份 apps.csv 里确实是纯数字如 0、1,000+…)。

正确的清洗应该带上 +:

1
2
df.Installs = df.Installs.astype(str).str.replace('[+,]', '', regex=True)
df.Installs = pd.to_numeric(df.Installs)

(13)Price 转数字

1
2
3
4
df_apps_clean.Price = df_apps_clean.Price.astype(str).str.replace('$', "")
df_apps_clean.Price = pd.to_numeric(df_apps_clean.Price)

df_apps_clean.sort_values('Price', ascending=False).head(20)

同样的两步——replace('$', "") + to_numeric。

注意 '$' 在正则里有特殊含义(行尾),但 .str.replace 默认按字面替换(regex=False),所以能正常去掉。

(14)过滤异常价格

1
2
df_apps_clean = df_apps_clean[df_apps_clean['Price'] < 250]
df_apps_clean.sort_values('Price', ascending=False).head(5)

为什么砍掉 >= 250? 因为排名前 20 的「最贵应用」里有一堆 $399.99 的「垃圾应用」(比如「I am rich」这类)——它们的价格不代表真实市场。

「过滤异常值」是数据清洗的必要一步——但阈值(250)是主观的,必须记录理由。

(15)估算营收

1
2
df_apps_clean['Revenue_Estimate'] = df_apps_clean.Installs.mul(df_apps_clean.Price)
df_apps_clean.sort_values('Revenue_Estimate', ascending=False)[:10]

Installs * Price = 「安装量 × 单价」——这是「营收」的粗略估算。

.mul() 是「乘法」的方法写法(等价于 Installs * Price)——优点是能处理「对齐缺失」的情况。

⚠️ 这个估算有三个大问题:

  1. Installs 是「区间下限」("10,000+" 意味着「至少 1 万」,可能 100 万);
  2. 付费应用也可能有内购(这份数据没体现);
  3. 免费应用的 Price 是 0,营收恒为 0——所以这个指标只能用于付费应用。

(16)分类统计:nunique + value_counts

1
2
df_apps_clean.Category.nunique()
top10_category = df_apps_clean.Category.value_counts()[:10]

33 个分类,取前 10 个「应用数量最多」的。

(17)竖柱状图 vs 横柱状图

1
2
3
4
5
bar = px.bar(
x = top10_category.index, # index = category name
y = top10_category.values)

bar.show()

竖柱:数量对比。

1
2
3
4
5
6
7
8
category_installs = df_apps_clean.groupby('Category').agg({'Installs': pd.Series.sum})
category_installs.sort_values('Installs', ascending=True, inplace=True)

h_bar = px.bar(
x = category_installs.Installs,
y = category_installs.index,
orientation='h',
title='Category Popularity')

orientation='h':横向柱状图——适合「分类名很长」的场景(横着放标签不会挤)。

sort_values(..., ascending=True, inplace=True):升序排——在横柱图里,最小值在底部、最大值在顶部(视觉上「最高」)。

(18)散点图:下载量 vs 竞争度

1
2
3
4
5
6
7
8
9
10
11
cat_number = df_apps_clean.groupby('Category').agg({'App': pd.Series.count})
cat_merged_df = pd.merge(cat_number, category_installs, on='Category', how="inner")

scatter = px.scatter(cat_merged_df,
x='App',
y='Installs',
title='Category Concentration',
size='App',
hover_name=cat_merged_df.index,
color='Installs'
)

这是全书信息密度最高的一张图:

  • x = 应用数量(竞争激烈程度);
  • y = 总下载量(市场大小);
  • 点大小 = 应用数量;
  • 颜色 = 下载量。

四个象限的含义:

位置 含义
左上(少应用、多下载)蓝海——竞争小、市场大
右下(多应用、少下载)红海——竞争大、市场小
右上大市场但竞争激烈
左下小众

这就是「选品分析」的雏形——Day 87/92 的商业分析思路一致。

(19)拆分嵌套值:str.split + stack

1
2
3
4
5
6
len(df_apps_clean.Genres.unique())
df_apps_clean.Genres.value_counts().sort_values(ascending=True)[:5]

stack = df_apps_clean.Genres.str.split(';', expand=True).stack()
print(f'We now have a single column with shape: {stack.shape}')
num_genres = stack.value_counts()

这是这一天最难的技巧:

Genres 的值是 "Action;Adventure;Fantasy"——一个格子装了三个值。

value_counts() 会把 "Action;Adventure;Fantasy" 当成一个整体——所以直接统计是错误的。

三步拆解:

① .str.split(';', expand=True)

按分号拆成多列——expand=True 让结果变成 DataFrame(每列一个 genre):

1
2
3
     0         1        2
0 Action Adventure Fantasy
1 Puzzle NaN NaN

② .stack()

把「宽表压回长列」——同时自动丢掉 NaN:

1
2
3
4
0  0    Action
1 Adventure
2 Fantasy
1 0 Puzzle

③ value_counts()

现在每个 genre 是一行,统计就对了——结果约 48 个真实 genre。

stack() 是「宽转长」的标准工具(unstack() 是反方向)。

(20)分组柱状图:免费 vs 付费

1
2
3
4
5
6
7
8
9
10
11
12
df_apps_clean.Type.value_counts()

df_free_vs_paid = df_apps_clean.groupby(["Category", "Type"],
as_index=False).agg({'App': pd.Series.count})
df_free_vs_paid.sort_values('App')

g_bar = px.bar(df_free_vs_paid,
x='Category',
y='App',
title='Free vs Paid Apps by Category',
color='Type',
barmode='group',)

groupby(["Category", "Type"]):多列分组——每个(分类, 类型)组合一行。

as_index=False:让分组键变成普通列(而不是索引)——这样 px.bar 能直接按列名取。

这是「Plotly 画图前必做」的一步:Plotly 需要列名,不要索引。

color='Type' + barmode='group':同一个 Category 下,Free 和 Paid 并排两根柱子。

(21)箱线图:付费应用的「下载损失」

1
2
3
4
5
6
7
8
9
10
box = px.box(df_apps_clean, 
y='Installs',
x='Type',
color='Type',
notched=True,
points='all',
title='How Many Downloads are Paid Apps Giving Up?'
)

box.update_layout(yaxis=dict(type='log'))

五个参数:

参数 含义
y='Installs'纵轴是下载量
x='Type'按免费/付费分组
notched=True箱体带凹槽(显示中位数置信区间)
points='all'每个数据点都画出来(能看到密集的离群点)
yaxis=dict(type='log')纵轴取对数

为什么要对数轴? 因为下载量从 0 到 10 亿,跨度 9 个数量级——线性轴下,绝大多数点会被压在底部一条线上。

结论:付费应用的中位下载量比免费低一到两个数量级——「付费 = 少下载」的证据。

(22)营收箱线图

1
2
3
4
5
6
7
8
9
10
11
df_paid_apps = df_apps_clean[df_apps_clean['Type'] == 'Paid']

box = px.box(df_paid_apps,
x='Category',
y='Revenue_Estimate',
title='How Much Can Paid Apps Earn?')

box.update_layout(xaxis_title='Category',
yaxis_title='Paid App Ballpark Revenue',
xaxis={'categoryorder':'min ascending'},
yaxis=dict(type='log'))

xaxis={'categoryorder':'min ascending'}:按「每类最小值」升序排列分类。

四种 categoryorder:

值 含义
'trace'按数据出现顺序
'category ascending'按字母
'total descending'按总量降序(最常用)
'min ascending' / 'max descending'按极值排序

(23)价格中位数 + 价格箱线图

1
2
3
4
5
6
7
8
9
10
11
df_paid_apps.Price.median()

box = px.box(df_paid_apps,
x='Category',
y="Price",
title='Price per Category')

box.update_layout(xaxis_title='Category',
yaxis_title='Paid App Price',
xaxis={'categoryorder':'max descending'},
yaxis=dict(type='log'))

median() 是「中位数」——比均值更抗异常值(前面砍掉 $250+ 就是为了这个)。

'max descending':按「每类最高价」降序——能看出哪些类敢定高价(比如「Personalization」类)。

这份代码的问题

  1. Installs 的 + 号没处理(to_numeric 在 "1,000+" 上会崩,这份数据恰好是纯数字)。
  2. px.pie 同时传 labels 和 names(旧 API 混新 API)。
  3. Revenue_Estimate 只对「付费应用」有意义,但算的时候包含免费应用(值为 0)。
  4. drop_duplicates(subset=[...]) 的列选择是主观的。
  5. Price < 250 的阈值没有依据说明。
  6. Genres 拆分后的 genre 总数与 unique() 的 114 个不一致——因为 unique() 数的是「组合」,不是「单个 genre」。这是很好的教学点。

README.md(8 行)

标题 Day 75 - Google Play Store App Analytics,知识点:Pandas、Plotly、Data Cleaning、Data Visualisation、Pie/Donut/Bar/Scatter/Box Charts。

五类图表全在这天出现:饼、环、柱、散点、箱线。

这一天是「数据清洗」最密集的一天——五个脏字段、五种清洗手法:

脏字段 清洗手法
Rating 有 NaNdropna()
重复行drop_duplicates(subset=...)
Installs 带逗号.str.replace + to_numeric
Price 带 $.str.replace + to_numeric
Genres 分号多值.str.split(expand=True).stack()

这五个套路,是「真实世界数据」的通用处理方法。

微信收款码 微信
支付宝收款码 支付宝
评论