import pandas as pd
import numpy as np
contents={"name": ['Bob', 'LiSa', 'Mary', 'Alan'],
"ID": [1, 2, ' ', None], # 输出 NaN
"age": [np.nan, 28, 38 , '' ], # 输出
"age02": [14, 26, 24 , 6],
"born": [pd.NaT, pd.Timestamp("1990-01-01"), pd.Timestamp("1980-01-01"), ''], # 输出 NaT
"sex": ['男', '女', '女', None,], # 输出 None
"hobbey":['打篮球', '打羽毛球', '打乒乓球', '',], # 输出
"money":[200.0, 240.0, 290.0, 300.0], # 输出
"weight":[140.5, 120.8, 169.4, 155.6], # 输出
"test01":[1, 2.123456789, 3.123456781011126, 4.123456789109999], # 输出
"test02":[1, 2.123456789, 3.123456781011126, 4.123456789109999], # 输出
}
data_frame = pd.DataFrame(contents)
# T1、直接创建 category类型数据
weight_mark=pd.Categorical(['thin','medium','medium','fat'],categories=['medium','fat'])
print(weight_mark)
# T2、利用分箱机制(结合max、mean、min实现二分类)动态添加 category类型数据
col_age_des=pd.Series(data_frame['age02']).describe()
age_ranges=[col_age_des['min']-1,col_age_des['mean'],col_age_des['max']+1]
age_labels=['Minors','Adults'] # 高于平均值的为胖
data_frame['age02_mark']=pd.cut(data_frame['age02'],age_ranges,labels=age_labels)
print(data_frame)
到此这篇关于详细介绍在pandas中创建category类型数据的几种方法的文章就介绍到这了,更多相关pandas创建category内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!