清洗代码如下。
- import pandas as pd
- import pymysql
-
- # 设置列名与数据对齐
- pd.set_option('display.unicode.ambiguous_as_wide', True)
- pd.set_option('display.unicode.east_asian_width', True)
- # 显示10列
- pd.set_option('display.max_columns', 10)
- # 显示10行
- pd.set_option('display.max_rows', 10)
- # 设置显示宽度为500,这样就不会在IDE中换行了
- pd.set_option('display.width', 2000)
-
- # 读取数据
- conn = pymysql.connect(host='localhost', user='root', password='774110919', port=3306, db='weibo', charset='utf8mb4')
- cursor = conn.cursor()
- sql = "select * from comments"
- db = pd.read_sql(sql, conn)
-
- # 清洗数据
- df = db['user_message'].str.split(' ', expand=True)
- # 用户名
- df['name'] = df[0]
- # 性别及地区
- df1 = df[1].str.split('/', expand=True)
- df['gender'] = df1[0]
- df['province'] = df1[1]
- # 用户ID
- df['id'] = db['user_id']
- # 评论信息
- df['comment'] = db['comment']
- # 点赞数
- df['praise'] = db['praise'].str.extract('(d+)').astype("int")
- # 微博数,关注数,粉丝数
- df2 = db['weibo_message'].str.split(' ', expand=True)
- df2 = df2[df2[0] != '未知']
- df['tweeting'] = df2[0].str.extract('(d+)').astype("int")
- df['follows'] = df2[1].str.extract('(d+)').astype("int")
- df['followers'] = df2[2].str.extract('(d+)').astype("int")
- # 评论时间
- df['time'] = db['date'].str.split(':', expand=True)[0]
- df['time'] = pd.Series([i+'时' for i in df['time']])
- df['day'] = df['time'].str.split(' ', expand=True)[0]
- # 去除无用信息
- df = df.ix[:, 3:]
- df = df[df['name'] != '未知']
- df = df[df['time'].str.contains("日")]
- # 随机输出10行数据
- print(df.sample(10))
输出数据。

随机输出十条,就大致能看出评论区是什么画风了。
四、数据可视化 (编辑:威海站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|