当您在数据帧上运行get_dummies
时,有没有好的方法来创建列名.例如,
import pandas as pd
# set up a dataframe with one numeric and two categocial columns
df = pd.DataFrame({
"numeric_1": [1, 2, 3, 4],
"cat_1": ['high', 'low', 'high', 'low'],
"cat_2": ['blue', 'blue', 'green', 'green']
})
# identify the categorical columns
categorical_colnames = ['cat_1', 'cat_2']
# get dummies
df = pd.get_dummies(df, categorical_colnames)
对于此数据帧,我希望看到:
[‘CAT_1_High’,‘CAT_1_Low’,‘CAT_2_Blue’,‘CAT_2_Green’]
我用来做这件事的代码很笨重,我想知道有没有更好的.我搜索了文档,似乎没有当你运行pd.get_dummies
时返回它的选项.以下是我使用的代码:
nominal_prefixes = [s + "_" for s in categorical_colnames]
nominal_colnames = []
for x in nominal_prefixes:
cols_x = [col for col in df if col.startswith(x)]
nominal_colnames.append(cols_x)
nominal_colnames = [item for sublist in nominal_colnames for item in sublist]
对于nominal_colnames
,我创建了我想要的 list ,但这很笨重,我希望有更好的东西.我不得不在我的代码中经常这样做,我想其他Pandas 用户也会这样做.我认为this question是类似的,但它没有回答我的问题.