如何将pandas中的onehot编码列重命名为各自的索引?

2024-10-02 14:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个用提供给我的代码对一些分类变量进行热编码的人。这行添加了一列0和1,名称的格式为prefix_categoricalValue

dataframe = pandas.concat([dataframe,pandas.get_dummies(dataframe[0], prefix='protocol')],axis=1).drop([0],axis=1)

我希望列的名称是它的索引,而不是prefix_categoricalValue。在

我知道我可以做一些类似df.rename(columns={'prefix_categoricalValue': '0'}, inplace=True)的操作,但我不确定如何对所有具有该前缀的列执行此操作。在

enter image description here

这是数据帧的一部分的示例。不管我是否决定保留本地的ė地址前缀,每个类别都会有它的名称。可以用索引重命名列吗?在

编辑:

我正在努力做到:

^{pr2}$

但我不太清楚为什么它不起作用


Tags: 代码名称dataframepandas编码getprefix格式
3条回答

IIUC公司

dummydf=pd.get_dummies(df.A)
dummydf.columns=['A']*dummydf.shape[1]
dummydf
Out[1171]: 
   A  A
0  1  0
1  0  1
2  1  0
df
Out[1172]: 
   A  B  C
0  a  b  1
1  b  a  2
2  a  c  3
import pandas as pd

# 'dataframe' is the name of your data frame in the question, so that's what I use
# in my code below, although I suggest using 'data' or something for it instead, 
# as 'DataFrame' is a keyword and its easy to make confusion. But anyway...

features = ['list of column names you want one-hot encoded']
# for example, features = ['Cars', 'Model, 'Year', ... ]

for f in features: 
    df = dataframe[[f]]

    df2 = (pd.get_dummies(df, prefix='', prefix_sep='')
                   .max(level=0, axis=1)
                   .add_prefix(f+' - '))  
    # the new feature names will be "<old_feature_name> - <categorical_value>"
    # for example, "Cars" will get transformed to "Cars - Minivan", "Cars - Truck", etc


    # add the new one-hot encoded column to the dataframe
    dataframe = pd.concat([dataframe, df2], axis=1)

    # you can remove the original columns, if you don't need them anymore (optional)
    dataframe = dataframe.drop([f], axis=1) 

假设你的前缀是local_address_0.0.0.0。以下代码根据列在dataframe中的出现顺序,将以指定前缀开头的列重命名为列所具有的索引:

prefix = 'local_address_0.0.0.0'
cols = list(dataframe)
for idx, val in enumerate(cols):
    if val.startswith(prefix):
        dataframe.rename(index=str, columns={val: idx}, inplace=True)

这将在控制台中显示警告:

^{pr2}$

但这只是一个警告,dataframe的列名会更新。如果要了解有关警告的详细信息,请参阅How to deal with SettingWithCopyWarning in Pandas?

如果有人知道如何在没有警告的情况下做同样的事情,请评论。在

相关问题 更多 >