设为首页 加入收藏

TOP

【pandas小技巧】--按类型选择列
2023-08-06 07:49:54 】 浏览:83
Tags:pandas

本篇介绍的是pandas选择列数据的一个小技巧。
之前已经介绍了很多选择列数据的方式,比如lociloc函数,按列名称选择,按条件选择等等。

这次介绍的是按照列的数据类型来选择列,按类型选择列可以帮助你快速选择正确的数据类型,提高数据分析的效率。

1. 类型种类

pandas列的数据类型主要有4大种类:

  1. number:数值类型,包括整数和浮点数
  2. object:主要是字符串类型
  3. catagory:分类类型
  4. datetime:日期类型

创建包含上述数据类型的测试数据:

import pandas as pd

df = pd.DataFrame(
    {
        "日期": [
            "2020/04/10",
            "2020/04/11",
            "2021/06/17",
            "2021/06/18",
            "2022/11/22",
            "2022/11/23",
        ],
        "年级": ["初一", "初二", "初一", "初二", "初一", "初二"],
        "学生": ["小红", "小华", "小明", "小李", "小汪", "小郑"],
        "名次": [1, 1, 2, 3, 1, 3],
        "平均成绩": [98.5, 95.5, 92.0, 89.5, 99.0, 87.5],
    },
)
df["日期"] = pd.to_datetime(df["日期"])
df["年级"] = df["年级"].astype("category")
print(df.dtypes)
df

image.png
image.png

2. 选择类型

按列的类型选择用 select_dtypes 函数。

2.1. 选择一个类型

选择一个类型时,用 include 参数指定列名。

df.select_dtypes(include="category")

image.png

number类型包含 intfloat

df.select_dtypes(include="number")

image.png

也可以指定 intfloat 选择整数或者浮点数

df.select_dtypes(include="int")
df.select_dtypes(include="float")

image.png

2.2. 选择多个类型

选择多个类型还是 include 参数,不过传入的值是列表

df.select_dtypes(include=["category", "datetime"])

image.png

2.3. 指定不选的类型

include参数是指定要选择的类型,如果要选择的类型比较多,我们可以通过exclude参数来设置不需要的类型。

df.select_dtypes(exclude="datetime")

image.png

exclude 参数也可以传入列表,设置多个不选择的类型。

df.select_dtypes(exclude=["category", "datetime"])

image.png

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python解释器及开发工具安装-wind.. 下一篇秋叶整合包如何安装Python包

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目