pandas cut: 如何将分类标签转换为字符串(否则无法导出为Excel)?

pandas cut: how to convert categorical labels to strings (otherwise cannot export to Excel)?

我用pandas.cut()将一个连续变量离散化成一个范围,然后按结果分组。

经过多次咒骂,因为我无法弄清楚哪里出了问题,我了解到,如果我不为 cut() 函数提供自定义标签,而是依赖默认值,那么输出无法导出到 excel。如果我试试这个:

import pandas as pd
import numpy as np    

writer = pd.ExcelWriter('test.xlsx')
wk = writer.book.add_worksheet('Test')

df= df= pd.DataFrame(np.random.randint(1,10,(10000,5)), columns=['a','b','c','d','e'])
df['range'] = pd.cut( df['a'],[-np.inf,3,8,np.inf] )
grouped=df.groupby('range').sum()
grouped.to_excel(writer, 'Export')
writer.close()

我得到:

raise TypeError("Unsupported type %s in write()" % type(token))
TypeError: Unsupported type <class 'pandas._libs.interval.Interval'> in write()
which it took me a while to decypher.

如果我改为分配标签:

df['range'] = pd.cut( df['a'],[-np.inf,3,8,np.inf], labels =['<3','3-8','>8'] )

然后一切正常。 关于如何在不分配自定义标签的情况下处理此问题的任何建议?在我工作的初始阶段,我倾向于不分配标签,因为我仍然不知道我想要多少个垃圾箱 - 这是一种反复试验的方法,并且每次尝试分配标签都非常耗时。

我不确定这是否可以算作一个错误,但至少它看起来像是一个没有记录的烦恼!

使用astype(str):

writer = pd.ExcelWriter('test.xlsx')
wk = writer.book.add_worksheet('Test')

df= df= pd.DataFrame(np.random.randint(1,10,(10000,5)), columns=['a','b','c','d','e'])
df['range'] = pd.cut( df['a'],[-np.inf,3,8,np.inf] ).astype(str)
grouped=df.groupby('range').sum()
grouped.to_excel(writer, 'Export')
writer.close()

excel中的输出:

range   a   b   c   d   e
(-inf, 3.0] 6798    17277   16979   17266   16949
(3.0, 8.0]  33150   28051   27551   27692   27719
(8.0, inf]  9513    5153    5318    5106    5412