pandas.get_dummies 的用法

pandas.get_dummies 的用法


get_dummies 是利用pandas实现one hot encode的方式。

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt
import torch 
from torch import nn 
from torch.utils.data import Dataset,DataLoader,TensorDataset

dftrain_raw = pd.read_csv('/content/eat_pytorch_in_20_days/data/titanic/train.csv')
dftest_raw = pd.read_csv('/content/eat_pytorch_in_20_days/data/titanic/test.csv')
dftrain_raw.head(10)

Pclass:乘客所持票类,有三种值(1,2,3) 【转换成onehot编码】
在这里插入图片描述

    dfdata = dftrain_raw
    dfresult= pd.DataFrame()
    #Pclass
    dfPclass = pd.get_dummies(dfdata['Pclass'])

get_dummies 后:在这里插入图片描述

    dfPclass.columns = ['Pclass_' +str(x) for x in dfPclass.columns ]
    dfresult = pd.concat([dfresult,dfPclass],axis = 1)
    dfresult

在这里插入图片描述
Embarked:乘客登船港口:S、C、Q(有缺失)【转换成onehot编码,四维度 S,C,Q,nan】

pd.get_dummies(dfdata['Embarked'],dummy_na=True)

在这里插入图片描述

dfEmbarked = pd.get_dummies(dfdata['Embarked'],dummy_na=True)
dfEmbarked.columns = ['Embarked_' + str(x) for x in dfEmbarked.columns]
dfresult = pd.concat([dfresult,dfEmbarked],axis = 1)

在这里插入图片描述

pd.get_dummies is a Python function from the pandas library that is used to create dummy variables from categorical data. It creates a new column for each unique category of a categorical variable, and assigns a value of 1 or 0 to each row depending on whether that row belongs to that category or not. This is useful for machine learning algorithms that require numerical input, as it converts non-numerical data into a numerical format. For example, if we have a dataset with a categorical variable "color" that has three categories: red, green, and blue, pd.get_dummies will create three new columns in the dataset called "color_red", "color_green", and "color_blue". Each row will have a value of 1 in the column that corresponds to its color, and 0 in the other two columns. The syntax for pd.get_dummies is: ``` pd.get_dummies(data, columns=None, prefix=None, prefix_sep='_', dummy_na=False, drop_first=False) ``` - data: the input pandas DataFrame or Series - columns: the name or list of names of the columns to encode. If not specified, all non-numerical columns will be encoded. - prefix: the prefix to add to the column names of the new dummy variables - prefix_sep: the separator to use between the prefix and the original column name - dummy_na: whether to create an additional column for missing values. If True, a column called "column_name_nan" will be created for each column with missing values. - drop_first: whether to drop the first column of each set of dummy variables to avoid multicollinearity. If True, the first column will be dropped.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值