一.对CSV文件进行简单的数据处理和分析
# coding=utf-8
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
# 设置pandas的显示选项,以便更好地查看数据
pd.set_option('display.max_rows', 500) # 设置最多显示的行数
pd.set_option('display.max_columns', 1000) # 设置最多显示的列数
pd.set_option('display.width', 1000) # 设置显示的宽度
# 定义文件路径
file_path = '911.csv'
# 读取csv文件
df = pd.read_csv(file_path)
# 从'title'列中提取分类信息,并去重
temp_list = df['title'].str.split(':').tolist()
cate_list = list(set([i[0] for i in temp_list]))
print(cate_list)
# 创建一个全为0的DataFrame,列名为分类名称
zeros_df = pd.DataFrame(np.zeros((df.shape[0], len(cate_list))), columns=cate_list)
# 遍历分类名称列表
for cate in cate_list:
# 如果'title'列包含该分类名称,则在对应的列中将相应行的值设为1
zeros_df[cate][df['title'].str.contains(cate)] = 1
# 计算每列的和,即每个分类的总数
sum_ret = zeros_df.sum(axis=0)
print(sum_ret)
以下是代码的主要步骤:
1. 导入必要的库:pandas用于数据处理,matplotlib用于绘图,numpy用于数值计算。
2. 设置pandas的显示选项,以便更好地查看数据。
3. 定义文件路径,并读取CSV文件到一个pandas DataFrame中。
4. 从'title'列中提取分类信息,并去重得到一个分类列表。
5. 创建一个全为0的DataFrame,列名为分类名称,行数与原始DataFrame相同。
6. 遍历分类名称列表,对于每个分类,如果'title'列包含该分类名称,则在对应的列中将相应行的值设为1。<