pandas学习 - get-dummies,drop,join函数

本文介绍了pandas中的get_dummies函数,用于将分类变量转化为哑变量,详细解释了参数用法。同时,讲解了drop函数删除行的操作,以及join函数如何在DataFrame间进行数据融合。通过实例说明了在不指定列名时,如何正确使用这些函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

get-dummies

将分类变量转换为哑变量/指示变量

pd.get_dummies(data, prefix=None, prefix_sep=’_’, dummy_na=False, columns=None, sparse=False, drop_first=False)

data为df或series,在未指定对data的某个列做one-hot时,get_dummies会自动识别data内类型为str的列,并做on-hot。prefix是为one-hot转变后的列命名,dunmmy_na是指是否将na类型也作为one-hot编码时的一个类型。

# 未指定哪一列做one-hot

df = pd.DataFrame({'A': ['A','B','C'], 'B': [1,2,3],
                        'C': [1, 2, 3]})
pd.get_dummies(df,prefix=['A'])

在这里插入图片描述
当data内的列均不为str且也未指定对data的哪一列做编码时,get_dummies会不作任何处理。

df = pd.DataFrame({'A': [1,2,2], 'B': [1,2,3],
                        'C': [1, 2, 3]})
pd.get_dummies(df,prefix=['A'])

在这里插入图片描述
这时若想对data的第一列做one-hot就得指定该列,然后将其余数据列合并

df = pd.DataFrame({'A': [1,2,2], 'B': [1,2,3],
                        'C': [1, 2, 3]})
a_hot = pd.get_dummies(df['A'])
a_hot.join(df[['B','C']])

在这里插入图片描述

df.drop

drop(labels, axis=0, level=None, inplace=False, errors=‘raise’)

axis=0 表示删除行

df.join

join(other, on=None, how=‘left’, lsuffix=’’, rsuffix=’’, sort=False)
必须是dataframe格式才可使用

Parametersusage
otherDataFrame, Series with name field set, or list of DataFrame Index should be similar to one of the columns in this one. If a Series is passed, its name attribute must be set, and that will be used as the column name in the resulting joined DataFrame
oncolumn name, tuple/list of column names, or array-like
how{‘left’, ‘right’, ‘outer’, ‘inner’} How to handle indexes of the two objects. Default: ‘left’ for joining on index, None otherwise * left: use calling frame’s index * right: use input frame’s index * outer: form union of indexes * inner: use intersection of indexes
lsuffixstring Suffix to use from left frame’s overlapping columns
rsuffixstring Suffix to use from right frame’s overlapping columns
sortboolean, default False Order result DataFrame lexicographically by the join key. If False, preserves the index order of the calling (left) DataFrame
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值