目录
1.读取csv文件
上图展示该数据集的部分数据,可见数据表是没有表头(即列名),因为在读取文件时,要标注header=None,否则会默认把第一行数据作为表头。
import pandas as pd
dataset = pd.read_csv('data/training.1600000.processed.noemoticon.csv', header=None, encoding='ISO-8859-1',engine='python')
2.查看读取后的数据表的相关信息
2.1 数据表的形状
dataset.shape # (1600000, 6)
(1600000, 6)表示有160万条记录,每条记录有6个特征
2.2 数据表信息
dataset.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1600000 entries, 0 to 1599999 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 0 1600000 non-null int64 1 1 1600000 non-null int64 2 2 1600000 non-null object 3 3 1600000 non-null object 4 4 1600000 non-null object 5 5 1600000 non-null object dtypes: int64(2), object(4) memory usage: 73.2+ MB
2.3 数据表描述:查看数据类型的列的各种数学值
dataset.describe()
2.4 查看列名
dataset.columns
因为该数据集本身就没有列名,因此系统会用0,1,2,3,4,5代替
Int64Index([0, 1, 2, 3, 4, 5], dtype='int64')
2.5 显示前5行
dataset.head()
2.6 统计某列的各类数据占比
# 统计列名为0的各类数据占比,其实也就是查看标签值得分布情况
dataset[0].value_counts()
0 800000 4 800000 Name: 0, dtype: int64
第二种方法也可以:
from collections import Counter
Counter(dataset[0])
Counter({0: 800000, 4: 800000})
3.新建一列
# 新建一列,把第一列复制
dataset['sentiment_category'] = dataset[0].astype('category')
4.将某列编码为数字
dataset['sentiment_category'].value_counts()
# 因为现在是0代表负面,4代表正面,
# 所以我们将其转换为0和1两个类别
dataset['sentiment'] = dataset['sentiment_category'].cat.codes
dataset['sentiment'].value_counts()
5.保存数据到csv文件
# 保存文件
dataset.to_csv('data/training-processed.csv',header=None,index=None) # 保存文件