一、条件
1.根据上一条文章中提取的数据(weibo_wanlian_myself.csv)
2.必要的库
import pandas as pd
import re
from pyecharts.charts import Grid
from pyecharts.charts import Pie, Bar, EffectScatter,WordCloud,Page
from pyecharts.components import Table
from pyecharts import options as opts
from pyecharts.globals import *
from snownlp import SnowNLP
from pyecharts import options as opts
from pyecharts.charts import WordCloud
from collections import Counter
import jieba
二、实现的目标
1.'分享'、'讨论' 和 '点赞'数分布柱形图
-
首先定义了三组分段(bins)和对应的标签(labels)。这些分段和标签用于将数据分成不同的范围,以便后续统计不同范围内数据的个数。
-
对数据进行预处理:
- 使用
apply
方法将数据列中的非整数值(例如空值或非数字字符串)转换为整数,如果无法转换,则将其设为0。 - 分别对 '分享'、'讨论' 和 '点赞' 列进行处理,并存储在名为
shares_list
、talks_list
和stars_list
的变量中。
- 使用
-
对 '分享'、'讨论' 和 '点赞' 列的数据进行离散化处理:
- 使用
pd.cut
函数对数据进行分段,分别使用前面定义的bins1
、bins2
和bins3
,并使用对应的标签(labels1
、labels2
和labels3
)来标识不同的分段。 - 使用
pd.Series().value_counts()
统计各个分段内数据的个数,并将结果转换为列表形式,分别存储在shares_counts
、talks_counts
和stars_counts
变量中。
- 使用
# 设置分段
bins1 = [0, 10, 20, 30, 40, 50, 60, 70]
bins2 = [0, 10, 20, 30, 40, 50, 60, 70]
bins3 = [0, 100, 200, 300, 400, 500, 1000, 2000]
# 设置标签
labels1 = ['0-60', '60-120', '120-180', '240-300', '360-420', '420-480', '480-540']
labels2 = ['0-60', '60-120', '120-180', '240-300', '360-420', '420-480', '480-540']
labels3 = ['0-100', '100-200', '200-300', '300-400', '400-500', '500-1000', '1000-2000']
# 将非整数类型的值设为0,并进行离散化处理
shares_list = df['分享'].apply(lambda x: int(x) if str(x).isdigit() else 0)
talks_list = df['讨论'].apply(lambda x: int(x) if str(x).isdigit() else 0)
stars_list = df['点赞'].apply(lambda x: int(x) if str(x).isdigit() else 0)
# 对分享数进行离散化
shares_segments = pd.cut(shares_list, bins1, labels=labels1)
shares_counts = pd.Series(shares_segments).value_counts(sort=False).values.tolist() # 统计各个分段的个数
# 对讨论数进行离散化
talks_segments = pd.cut(talks_list, bins2, labels=labels2)
talks_counts = pd.Series(talks_segments).value_counts(sort=False).values.tolist() # 统计各个分段的个数
# 对点赞数进行离散化
stars_segments = pd.cut(stars_list, bins3, labels=labels3)
stars_counts = pd.Series(stars_segments).value_counts(sort=False).values.tolist() # 统计各个分段的个数