【问题标题】:Pandas - After I created dummy columns how do I given a new vector get the dummy representation?Pandas - 创建虚拟列后,如何给定一个新向量以获得虚拟表示?
【发布时间】:2018-07-20 10:40:35
【问题描述】:

我的一些列包含文本分类值,例如 "did_do_something" 可能值为 "true" 或 "false" 或另一列可能是 "browser_type" 可能值为 "chrome", "safari" 但我也有其他包含数字类别“枚举”的列,例如“version_type”,其值可能类似于"1" ,"2" ,"3" ,"4",然后只有普通数字列,例如“age”,它只获得一个数字值并且应该保持不变。

我在这里查看了pandas 文档https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

特别是这个标志:

columns : 类似列表,默认无

要编码的 DataFrame 中的列名。如果列是无,那么 所有具有 object 或 category dtype 的列都将被转换。

我的虚拟处理如下所示:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

data_csv_file = 'data/data.csv'

data = pd.read_table(data_csv_file,delimiter = ",").dropna()

# this is the column containing the label for the row
label_column = 'converted_pixel'

# these columns SHOULD NOT be encoded since they are read numeric values
numeric_columns = ['campaign_frequency','user_age_days']

# all the other columns which are not label or numeric should be dummy encoded
dummy_columns = [a for a in data.columns if a != label_column and a not in numeric_columns]

# create the new processed data frame with the dummy columns
processed_dummy_data = pd.get_dummies(data,columns = dummy_columns)

处理后的数据框从原来的 21 列中产生了大约 1000 列。

我的问题是从原始数据帧中得到一个向量,我怎样才能从生成的虚拟中得到它的虚拟编码?

由于虚拟数据框这么大,我一个人做这个是不合理的。

我正在寻找类似的 API

dummy_encoded_vector = get_dummy_encoding(vector_from_original_dataframe_encoding, processed_dummy_data)

【问题讨论】:

    标签: python pandas numpy scikit-learn dummy-variable


    【解决方案1】:

    您可以使用str.contains

    df=pd.DataFrame({'A':list('abcde'),'B':list('abcde')})
    
    s=pd.get_dummies(df)
    
    yourcol='A'
    
    s.loc[:,s.columns.str.contains(yourcol+'_')]
    
    Out[117]: 
       A_a  A_b  A_c  A_d  A_e
    0    1    0    0    0    0
    1    0    1    0    0    0
    2    0    0    1    0    0
    3    0    0    0    1    0
    4    0    0    0    0    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 2014-09-16
      • 2015-08-11
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 2012-09-27
      • 2023-01-16
      相关资源
      最近更新 更多