資料讀取與資料分析(pandas)
資料讀取(利用pandas讀取)
import pandas as pd
train_df = pd.read_csv('路徑/train_set.csv', sep='\t', nrows=10000)
分隔符sep,為每列分割的字元,設定為\t即可;
讀取行數nrows,為此次讀取檔案的函數,是數值類型(由于資料集比較大,建議先設定為10000);
資料分析
train_df[‘text_len’] =train_df[‘text’].apply(lambda x: len(x.split(’ ')))#以空格分割每個單詞
print(train_df[‘text_len’].describe())
結果:
count 10000.000000
mean 908.766300
std 1033.708515
min 15.000000
25% 375.000000
50% 672.500000
75% 1123.000000
max 44665.000000
Name: text_len, dtype: float64
繪制直方圖
import matplotlib.pyplot as plt#導入matplotlib.pyplot
_ = plt.hist(train_df['text_len'], bins=200)
plt.xlabel('Text char count')
plt.title("Histogram of char count")
plt.show()
結果:

新聞類别分布
train_df[‘label’].value_counts().plot(kind=‘bar’)
plt.title(‘News class count’)
plt.xlabel(“category”)
plt.plot()
字元分布統計
>>> from collections import Counter
>>> all_lines = ' '.join(list(train_df['text']))
>>> word_count = Counter(all_lines.split(" "))
>>> word_count = sorted(word_count.items(), key=lambda d:d[1], reverse = True)
>>> print(len(word_count))
5340
>>> print(word_count[0])
('3750', 373091)
>>> print(word_count[-1])
('6577', 1)