首页 > 解决方案 > 获取具有对象或分类数据类型的列名列表

问题描述

我的目标是获取一个列表对象:['assetCode', 'assetName'],其中内容是Panda.series基于多个条件检索的 a 的标签。我试过:

tmp3 = datatype[datatype == 'object' | datatype == 'category'].index # extract label from Pandas.series

这给出了错误:TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]

然而,虽然不太优雅,但我能够找到以下两个可行的解决方案:

tmp2 = datatype[datatype == 'object'].index # extract label from Pandas.series
tmp2[0]
'assetCode'


tmp1 = datatype[datatype == 'category'].index # extract label from Pandas.series
tmp1[0]
'assetName'

如何将这两个字符串组合成一个列表对象?有没有比我尝试实现的更好的方法来实现这个目标?

标签: pythonpandasdataframetypes

解决方案


设置

df

   A  B  C
0  8  4  2
1  8  8  6
2  8  5  2

datatype = df.dtypes
datatype

A      object
B    category
C       int64
dtype: object

看起来您正在尝试从某些 DataFrame 中选择对象和分类列(此处未显示)。要修复您的代码,请使用:

tmp3 = datatype[(datatype == 'object') | (datatype == 'category')].index.tolist()
tmp3
#  ['A', 'B']

由于按位运算符具有更高的优先级,因此您需要在 ORing 掩码之前使用括号。之后,索引工作正常。

要获取列表,请调用.index.tolist()


另一个解决方案是select_dtypes

df.select_dtypes(include=['object', 'category'])

   A  B
0  8  4
1  8  8
2  8  5

df.select_dtypes(include=['object', 'category']).columns
# ['A', 'B']

这避免了对中间datatype系列的需要。


推荐阅读