将分类 Pandas 系列转换为字符串的快速方法

Fast way of turning categorical Pandas series to string

我有一个分类系列。

目前我正在使用以下代码映射到字符串。

import pandas as pd
import numpy as np
test = np.random.rand(int(5e6)) 
test[0] = np.nan          
test_cut = pd.cut(test,(-np.inf,0.2,0.4,np.inf))   
test_str = test_cut.astype('str')
test_str[test_str.isna()] = 'missing'

这个 astype('str') 操作很慢,有没有办法加快速度?

根据下面的 link,我了解到 apply 比 astype 快。我尝试了以下方法。

test_str = test_cut.apply(str)    
#AttributeError: 'Categorical' object has no attribute 'apply'

test_str = test_cut.map(str)   
# still categorical type

test_str = test_cut.values.astype(str)  
# AttributeError: 'Categorical' object has no attribute 'values'

我不关心类别的确切字符串表示形式,只关心组被保留并转换为字符串。

作为替代方案,有没有办法在 test_cut 分类 'Missing'(或其他东西)中定义一个新类别,并在 'test' 中设置 'missing' 个案=] 到这个类别?

# some code to create 'MISSING' category
test_cat[test_str.isna()] = 'MISSING'

使用 labels 参数代替 pd.Intevals:

生成字符串
breaks = [-np.inf, .2, .4, np.inf]
test_cut = pd.cut(test,breaks, labels=pd.IntervalIndex.from_breaks(breaks).astype(str)) 

尝试使用此代码计时。