Pandas基础教程学习(八)

Pandas基础教程学习(八)

Pandas基础(七):文本数据的类型、拆分、拼接、替换、匹配、提取等方法

DataWhale第十四期组队学习:[Joyful-Pandas](

一、category的创建及其性质

1.1 分类变量的创建

用Seires创建

pd.Series(["a", "b", "c", "a"], dtype="category")
'''
0    a
1    b
2    c
3    a
dtype: category
Categories (3, object): [a, b, c]
'''

对DataFrame指定类型创建

temp_df = pd.DataFrame({
     'A':pd.Series(["a", "b", "c", "a"], dtype="category"),'B':list('abcd')})
temp_df.dtypes
'''
A    category
B      object
dtype: object
'''

利用内置Categorical类型创建

cat = pd.Categorical(["a", "b", "c", "a"], categories=['a','b','c'])
pd.Series(cat)
'''
0    a
1    b
2    c
3    a
dtype: category
Categories (3, object): [a, b, c]
'''

利用cut函数创建

cut函数创建的分类默认为有序分类变量

pd.cut(np.random.randint(0,60,5), [0,10,30,60])
'''
[(10, 30], (30, 60], (10, 30], (30, 60], (30, 60]]
Categories (3, interval[int64]): [(0, 10] < (10, 30] < (30, 60]]
'''

pd.cut(np.random.randint(0,60,5), [0,10,30,60], 
       right=False, labels=['0-10','10-30','30-60'])
'''
[30-60, 30-60, 30-60, 0-10, 0-10]
Categories (3, object): [0-10 < 10-30 < 30-60]
'''

1.2 分类变量的结构

一个分类变量包括三个部分:元素值(values)、分类类别(categories)、是否有序(order)

下面介绍如何修改或获取这些属性

describe方法()

描述一个分类序列的情况,包括

  • 缺失值个数count
  • 元素值类别数(不是分类类别数)unique
  • 最多次出现的元素及其频数top、freq
s = pd.Series(pd.Categorical(["a", "b", "c", "a",np.nan], categories=['a','b','c','d']))
s.describe()
'''
count     4
unique    3
top       a
freq      2
dtype: object
'''

categories和ordered属性

# 查看分类类别
s.cat.categories
'''
Index(['a', 'b', 'c', 'd'], dtype='object')
'''

# 是否排序
s.cat.ordered # False

1.3 类别的修改

# 修改分类,但本身值不会变化
s = pd.Series(pd.Categorical(["a", "b", "c", "a",np.nan], categories=['a','b','c','d']))
s.cat.set_categories(['new_a','c'])
'''
0    NaN
1    NaN
2      c
3    NaN
4    NaN
dtype: category
Categories (2, object): [new_a, c]
'''

# 也可以通过参数设置顺序
pd.Series(["a", "d", "c", "a"]).astype('category').cat.set_categories(['a','c','d'],ordered=True)
# 修改分类,会把值和分类同时进行修改
s = pd.Series(pd.Categorical(["a", "b", "c", "a",np.nan], categories=['a','b','c','d']))
s.cat.rename_categories(['new_%s'%i for i in s.cat.categories])
'''
0    new_a
1    new_b
2    new_c
3    new_a
4      NaN
dtype: category
Categories (4, object): [new_a, new_b, new_c, new_d]
'''

# 也可以使用字典来实现
s.cat.rename_categories({
     'a':'new_a','b':'new_b'})
# 添加新的类
s = pd.Series(pd.Categorical(["a", "b", "c", "a",np.nan], categories=['a','b','c','d']))
s.cat.add_categories(['e'])
# 移除指定类
s = pd.Series(pd.Categorical(["a", "b", "c", "a",np.nan], categories=['a','b','c','d']))
s.cat.remove_categories(['d'])
# 删除元素值未出现的分类类型
s = pd.Series(pd.Categorical(["a", "b", "c", "a",np.nan], categories=['a','b','c','d']))
s.cat.remove_unused_categories()

二、分类变量的排序

2.1 序的建立

# 将序列转为有序变量,可以利用as_ordered方法
s = pd.Series(["a", "d", "c", "a"]).astype('category').cat.as_ordered()
'''
0    a
1    d
2    c
3    a
dtype: category
Categories (3, object): [a < c < d]
'''

# 退化为无序变量,只需要使用as_unordered
s.cat.as_unordered()
'''
0    a
1    d
2    c
3    a
dtype: category
Categories (3, object): [a, c, d]
'''

# 重设序与序的方向,但新设置的分类必须与原分类为同一集合
s = pd.Series(["a", "d", "c", "a"]).astype('category')
s.cat.reorder_categories(['a','c','d'],ordered=True)

2.2 排序

s = pd.Series(np.random.choice(['perfect','good','fair','bad','awful'],
                               50)).astype('category')
s.cat.set_categories(['perfect','good','fair',
                      'bad','awful'][::-1],ordered=True).head()

# 值排序和索引排序都是适用的
s.sort_values(ascending=False).head()
df_sort = pd.DataFrame({
     'cat':s.values,
                        'value':np.random.randn(50)}).set_index('cat')
df_sort.head()
df_sort.sort_index().head()

三、分类变量的比较操作

3.1 与标量或等长序列的比较

s = pd.Series(["a", "d", "c", "a"]).astype('category')
'''
0     True
1    False
2    False
3     True
dtype: bool
'''

s == list('abcd')

3.2 与另一分类变量的比较

等式判别

s = pd.Series(["a", "d", "c", "a"]).astype('category')
s == s
s != s

s_new = s.cat.set_categories(['a','d','e'])
#s == s_new #报错

不等式判别

两个分类变量的不等式判别需要满足两个条件:① 分类完全相同 ② 排序完全相同

s = pd.Series(["a", "d", "c", "a"]).astype('category')
#s >= s #报错
s = pd.Series(["a", "d", "c", "a"]).astype('category').cat.reorder_categories(['a','c','d'],ordered=True)
s >= s

你可能感兴趣的:(Pandas,python,数据分析)