python astype category_利用Python进行数据分析(11)-高阶应用category

本文中介绍的是pandas的高阶应用-分类数据category​

image

分裂数据Categorical

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

使用背景和目标

一个列中经常会包含重复值,这些重复值是一个小型的不同值的集合。

unique()和value_counts()能够从数组中提取到不同的值并分别计算它们的频率

values = pd.Series([“apple”,”orange”,”apple”,”apple”] * 2)

values

0 apple

1 orange

2 apple

3 apple

4 apple

5 orange

6 apple

7 apple

dtype: object

pd.unique(values) # 查看不同的取值情况

array([‘apple’, ‘orange’], dtype=object)

pd.value_counts(values) # 查看每个值的个数

apple 6

orange 2

dtype: int64

维度表

维度表包含了不同的值,将主要观测值存储为引用维度表的整数键

values = pd.Series([0,1,0,0] * 2)

dim = pd.Series([“apple”,”orange”])

values

0 0

1 1

2 0

3 0

4 0

5 1

6 0

7 0

dtype: int64

dim

0 apple

1 orange

dtype: object

take方法-分类(字典编码展现)

不同值的数组被称之为数据的类别、字典或者层级

dim.take(values)

0 apple

1 orange

0 apple

0 apple

0 apple

1 orange

0 apple

0 apple

dtype: object

使用Categorical类型

fruits = [“apple”,”orange”,”apple”,”apple”] * 2

N = len(fruits)

df = pd.DataFrame({“fruit”:fruits, # 指定每列的取值内容

“basket_id”:np.arange(N),

“count”:np.random.randint(3,15,size=N),

“weight”:np.random.uniform(0,4,size=N)},

columns=[“basket_id”,”fruit”,”count”,”weight”]) # 4个属性值

df

image.png

df[“fruit”]

0 apple

1 orange

2 apple

3 apple

4 apple

5 orange

6 apple

7 apple

Name: fruit, dtype: object

如何生成Categorical实例

fruit_cat = df[“fruit”].astype(“category”) # 调用函数改变

fruit_cat # 变成pd.Categorical的实例

0 apple

1 orange

2 apple

3 apple

4 apple

5 orange

6 apple

7 apple

Name: fruit, dtype: category

Categories (2, object): [apple, orange]

c = fruit_cat.values

c

[apple, orange, apple, apple, apple, orange, apple, apple]

Categories (2, object): [apple, orange]

两个属性:categories + codes

print(c.categories)

print(“—–“)

print(c.codes)

Index([‘apple’, ‘orange’], dtype=’object’)

Original: https://blog.csdn.net/weixin_35899510/article/details/112905821
Author: BLACK枪骑兵
Title: python astype category_利用Python进行数据分析(11)-高阶应用category

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/740959/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球