【问题标题】:Get list of column names having either object or categorical dtype获取具有对象或分类数据类型的列名列表
【发布时间】:2021-07-12 22:20:08
【问题描述】:

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

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'

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

【问题讨论】:

  • 这是由于运算符优先级,您必须在每个条件之间放置一个括号,如下面的答案所示。

标签: python pandas dataframe types


【解决方案1】:

设置

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']

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

要获取列表,请致电.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 系列的需求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2012-06-16
    • 2020-09-14
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多