可以为多列设置类别和类型吗?

Setting category and type for multiple columns possible?

我有一个数据集,其中包含 6 列 TIME1TIME6,等等。对于其中的每一个,我都需要应用下面的代码(显示为 2 列)。 LISTED 是这些列中可能出现的元素的准备列表。

有没有办法不用写相同的 2 行 6 次?

df['PART1'] = df['TIME1'].astype('category')
df['PART1'].cat.set_categories(LISTED, inplace=True)

df['PART2'] = df['TIME2'].astype('category')
df['PART2'].cat.set_categories(LISTED, inplace=True)

对于astype(第一行代码),我尝试了以下方法:

for col in ['TIME1', 'TIME2', 'TIME3', 'TIME4', 'TIME5', 'TIME6']:
    df_col = df[col].astype('category')

我认为这可行(不确定如何在整个代码不工作的情况下进行检查)。但是我怎么能用 set_categories 等对第二行代码做类似的事情呢?

简而言之,我正在寻找 short/more 优雅的东西,只需复制和修改相同的 2 行 6 次。 我是 python 的新手,非常感谢任何帮助。

使用 python 2.7 和 pandas 0.24.2

是的,这是可能的!我们可以通过创建 CategoricalDtype

一次性将多列的 dtype 更改为分类
i = pd.RangeIndex(1, 7).astype(str)
df['PART' + i] = df['TIME' + i].astype(pd.CategoricalDtype(LISTED))