python中字符串离散化的例子

'''

问题:
1、假设DataFrame中有一列名为type,其字段中内容为a,b,c 等用,隔开的值,如:
type
a,b,c
a,f,x
b,c,e
...
统计type中每个类型出现的次数 并绘图
'''

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt


# 读取数据
df = pd.read_csv("文件路径/文件名")


#统计分类的列表
temp_list = df["type"].str.split(",").tolist()
type_list = list(set([i for j in temp_list for i in j]))


# 构造全为0的数组
zeros_df = pd.DataFrame(np.zeros((df.shape[0],len(type_list))),columns=type_list)
# print(zeros_df)


# 给每个type出现分类的位置赋值为1
for i in range(df.shape[0]):
zeros_df.loc[i,temp_list[i]] = 1


# 统计每个分类type的数量和
type_count = zeros_df.sum(axis=0)
print(type_count)


# 排序
type_count = type_count.sor_values()
_x = type_count.index
_y = type_count.values

# 绘图
# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)
plt.bar(range(len(_x)),_y) #绘制条形图
plt.xticks(range(_x),_x)
plt.show()

猜你喜欢

转载自www.cnblogs.com/gaojr/p/12082623.html
今日推荐