4.6 Pandas中的Dataframe数据选取(二)(Python)

目录

前言

略。。。

一、初期数据准备

1. 初期数据定义

# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd

data = {
    'name': ['NAME0', 'NAME1', 'NAME2', 'NAME3', 'NAME4', 'NAME5', 'NAME6', 'NAME7', 'NAME8', 'NAME9'],

    'age': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],

    'weight': ["weight0", 101, 102, np.nan, np.nan, 105, np.nan, 107, 108, 109],

    'is_single_dog': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']
}

indexs = ['index0', 'index1', 'index2', 'index3', 'index4', 'index5', 'index6', 'index7', 'index8', 'index9']

df = pd.DataFrame(data, index=indexs)

print(df)

控制台输出结果:

         name  age   weight is_single_dog
index0  NAME0    0  weight0           yes
index1  NAME1    1      101           yes
index2  NAME2    2      102            no
index3  NAME3    3      NaN           yes
index4  NAME4    4      NaN            no
index5  NAME5    5      105            no
index6  NAME6    6      NaN            no
index7  NAME7    7      107           yes
index8  NAME8    8      108            no
index9  NAME9    9      109            no

二、Dataframe中的数据列选取

1. 列选取(单维度选取)

① 标签索引, 选取单个列
# 选取第一列df数据
df_column_1 = df['name']

print(df_column_1)

控制台输出结果:

index0    NAME0
index1    NAME1
index2    NAME2
index3    NAME3
index4    NAME4
index5    NAME5
index6    NAME6
index7    NAME7
index8    NAME8
index9    NAME9
Name: name, dtype: object

② 标签列表, 选取多个列
# 选取第二列和第三列df数据
df_column_2_and_3 = df[['age', 'weight']]

print(df_column_2_and_3)

控制台输出结果:

        age   weight
index0    0  weight0
index1    1      101
index2    2      102
index3    3      NaN
index4    4      NaN
index5    5      105
index6    6      NaN
index7    7      107
index8    8      108
index9    9      109

③ lambda表达式, 选取单个列
# 选取第三列df数据
df_column_3 = df[lambda df: df.columns[2]]

print(df_column_3)

控制台输出结果:

index0    weight0
index1        101
index2        102
index3        NaN
index4        NaN
index5        105
index6        NaN
index7        107
index8        108
index9        109
Name: weight, dtype: object

④ lambda表达式, 选取多个列,前闭后闭 [ , ]
# 选取第三列到第四列df数据
df_column_3_to_4 = df[lambda df: df.columns[2: 4]]

print(df_column_3_to_4)

控制台输出结果:

         weight is_single_dog
index0  weight0           yes
index1      101           yes
index2      102            no
index3      NaN           yes
index4      NaN            no
index5      105            no
index6      NaN            no
index7      107           yes
index8      108            no
index9      109            no

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ibun.song

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值