Skip to content Skip to sidebar Skip to footer

Get List Of Column Names Having Either Object Or Categorical Dtype

My goal is to get a list object: ['assetCode', 'assetName'], where the contents are the labels of a Panda.series that are retrieved based on more than one condition. I tried: tmp3

Solution 1:

Setup

df

   A  B  C
084218862852

datatype = df.dtypes
datatype

A      object
B    category
C       int64
dtype:object

It looks like you are trying to select object and categorical columns from some DataFrame (not shown here). To fix your code, use:

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

Since bitwise operators have higher precedence, you will need to use parentheses before ORing the masks. After that, indexing works fine.

To get a list, call .index.tolist().


Another solution is select_dtypes:

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

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

This circumvents the need for an intermediate datatype series.

Post a Comment for "Get List Of Column Names Having Either Object Or Categorical Dtype"