Python提取数据集中的数值变量/分类变量

26 篇文章 0 订阅

问题描述:

如何快速提取出数据集里的数值型变量或者分类变量?比如提取出所有float格式的数据。


解决方法:

#找出不是数值类型的列
categorical_features_indices=np.where(x.dtypes != np.float)[0]
#提取分类变量
categorical_features=x.iloc[categorical_features_indices]
#提取数值型变量,直接将分类变量删除
numeric_variable=x.drop(x.columns[categorical_features_indices],axis=1)

注意! 是根据变量格式float提取。如果是数字但是格式是int,依旧会被归类为分类变量。

完整代码:

例如,需要提取泰坦尼克中的数值变量/分类变量,不想要做数据类型转换,直接提取数据作为练习。

#导入数据集
x=pd.read_csv('train.csv')
x.dropna(inplace=True) #因为y从x导出,所以需要先删除缺失值
y=x.pop('Survived')

#查看数据类型
x.dtypes

在这里插入图片描述

#找出不是数值类型的列
categorical_features_indices=np.where(x.dtypes != np.float)[0]
#查看结果
categorical_features_indices

结果输出分类变量所在的位置:array([ 0, 1, 2, 3, 5, 6, 7, 9, 10])

#提取分类变量
categorical_features=x.iloc[categorical_features_indices]
#提取数值型变量,直接将分类变量删除
numeric_variable=x.drop(x.columns[categorical_features_indices],axis=1)
#查看结果
numeric_variable

在这里插入图片描述

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值