Python酷库之旅-第三方库Pandas(119)

news2024/9/18 22:54:01

目录

一、用法精讲

526、pandas.DataFrame.head方法

526-1、语法

526-2、参数

526-3、功能

526-4、返回值

526-5、说明

526-6、用法

526-6-1、数据准备

526-6-2、代码示例

526-6-3、结果输出

527、pandas.DataFrame.idxmax方法

527-1、语法

527-2、参数

527-3、功能

527-4、返回值

527-5、说明

527-6、用法

527-6-1、数据准备

527-6-2、代码示例

527-6-3、结果输出

528、pandas.DataFrame.idxmin方法

528-1、语法

528-2、参数

528-3、功能

528-4、返回值

528-5、说明

528-6、用法

528-6-1、数据准备

528-6-2、代码示例

528-6-3、结果输出

529、pandas.DataFrame.last方法

529-1、语法

529-2、参数

529-3、功能

529-4、返回值

529-5、说明

529-6、用法

529-6-1、数据准备

529-6-2、代码示例

529-6-3、结果输出

530、pandas.DataFrame.reindex方法

530-1、语法

530-2、参数

530-3、功能

530-4、返回值

530-5、说明

530-6、用法

530-6-1、数据准备

530-6-2、代码示例

530-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

526、pandas.DataFrame.head方法
526-1、语法
# 526、pandas.DataFrame.head方法
pandas.DataFrame.head(n=5)
Return the first n rows.

This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it.

For negative values of n, this function returns all rows except the last |n| rows, equivalent to df[:n].

If n is larger than the number of rows, this function returns all rows.

Parameters:
n
int, default 5
Number of rows to select.

Returns:
same type as caller
The first n rows of the caller object.
526-2、参数

526-2-1、n(可选,默认值为5)整数,表示要返回的行数,通过指定n的值,可以控制返回的数据行数。默认情况下,n=5,也就是返回前5行。当n为正整数时,它返回从头开始的n行;当n为负数时,则会返回排除最后|n|行的数据。

526-3、功能

        用于返回数据框的前几行,它通常用于快速查看数据框的头几行数据,以便了解数据的结构、列的名称及数据分布。

526-4、返回值

        返回类型为pandas.DataFrame,即原始数据框的一个子集,包含前n行数据,如果数据框的行数小于n,则返回整个数据框。

526-5、说明

        无

526-6、用法
526-6-1、数据准备
526-6-2、代码示例
# 526、pandas.DataFrame.head方法
import pandas as pd
data = {'A': range(10), 'B': range(10, 20)}
df = pd.DataFrame(data)
# 返回前5行
print(df.head())
526-6-3、结果输出
# 526、pandas.DataFrame.head方法
#    A   B
# 0  0  10
# 1  1  11
# 2  2  12
# 3  3  13
# 4  4  14
527、pandas.DataFrame.idxmax方法
527-1、语法
# 527、pandas.DataFrame.idxmax方法
pandas.DataFrame.idxmax(axis=0, skipna=True, numeric_only=False)
Return index of first occurrence of maximum over requested axis.

NA/null values are excluded.

Parameters:
axis{0 or ‘index’, 1 or ‘columns’}, default 0
The axis to use. 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise.

skipnabool, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.

numeric_onlybool, default False
Include only float, int or boolean data.

New in version 1.5.0.

Returns:
Series
Indexes of maxima along the specified axis.

Raises:
ValueError
If the row/column is empty.
527-2、参数

527-2-1、axis(可选,默认值为0){0或'index', 1或'columns'},如果是0或'index',则沿着每一列查找最大值的索引;如果是1或'columns',则沿着每一行查找最大值的索引。

527-2-2、skipna(可选,默认值为True)布尔值,如果为True,计算时会忽略NaN值;如果为False,遇到NaN值时将返回NaN。

527-2-3、numeric_only(可选,默认值为False)布尔值,如果为True,只考虑数值型数据;如果为False,则包括所有类型的数据,可能在含有非数值类型数据的列中返回错误。

527-3、功能

        用于定位DataFrame中最大值所在的行索引(如果按列查找)或列索引(如果按行查找)。

527-4、返回值

        返回一个Series,其索引是原DataFrame的列索引(如果按列查找),或者行索引(如果按行查找),值是对应列(或行)中最大值的索引位置。

527-5、说明

        无

527-6、用法
527-6-1、数据准备
527-6-2、代码示例
# 527、pandas.DataFrame.idxmax方法
import pandas as pd
# 创建一个示例DataFrame
data = {
    'A': [1, 3, 5],
    'B': [4, 2, 8],
    'C': [7, None, 6]
}
df = pd.DataFrame(data)
# 查找每一列最大值的索引
max_indices = df.idxmax(axis=0)
print(max_indices)
527-6-3、结果输出
# 527、pandas.DataFrame.idxmax方法
# A    2
# B    2
# C    0
# dtype: int64
528、pandas.DataFrame.idxmin方法
528-1、语法
# 528、pandas.DataFrame.idxmin方法
pandas.DataFrame.idxmin(axis=0, skipna=True, numeric_only=False)
Return index of first occurrence of minimum over requested axis.

NA/null values are excluded.

Parameters:
axis{0 or ‘index’, 1 or ‘columns’}, default 0
The axis to use. 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise.

skipnabool, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.

numeric_onlybool, default False
Include only float, int or boolean data.

New in version 1.5.0.

Returns:
Series
Indexes of minima along the specified axis.

Raises:
ValueError
If the row/column is empty.
528-2、参数

528-2-1、axis(可选,默认值为0){0或'index', 1或'columns'},如果是0或'index',则沿着每一列查找最小值的索引;如果是1或'columns',则沿着每一行查找最小值的索引。

528-2-2、skipna(可选,默认值为True)布尔值,如果为True,计算时会忽略NaN值;如果为False,遇到NaN值时将返回NaN。

528-2-3、numeric_only(可选,默认值为False)布尔值,如果为True,只考虑数值型数据;如果为False,则包括所有类型的数据,可能在含有非数值类型数据的列中返回错误。

528-3、功能

           用于定位DataFrame中最小值所在的行索引(如果按列查找)或列索引(如果按行查找)。

528-4、返回值

        返回一个Series,其索引是原DataFrame的列索引(如果按列查找),或者行索引(如果按行查找),值是对应列(或行)中最小值的索引位置。

528-5、说明

        无

528-6、用法
528-6-1、数据准备
528-6-2、代码示例
# 528、pandas.DataFrame.idxmin方法
import pandas as pd
# 创建一个示例DataFrame
data = {
    'A': [1, 3, 5],
    'B': [4, 2, 8],
    'C': [7, None, 6]
}
df = pd.DataFrame(data)
# 查找每一列最小值的索引
min_indices = df.idxmin(axis=0)
print(min_indices)
528-6-3、结果输出
# 528、pandas.DataFrame.idxmin方法
# A    0
# B    1
# C    2
# dtype: int64
529、pandas.DataFrame.last方法
529-1、语法
# 529、pandas.DataFrame.last方法
pandas.DataFrame.last(offset)
Select final periods of time series data based on a date offset.

Deprecated since version 2.1: last() is deprecated and will be removed in a future version. Please create a mask and filter using .loc instead.

For a DataFrame with a sorted DatetimeIndex, this function selects the last few rows based on a date offset.

Parameters:
offset
str, DateOffset, dateutil.relativedelta
The offset length of the data that will be selected. For instance, ‘3D’ will display all the rows having their index within the last 3 days.

Returns:
Series or DataFrame
A subset of the caller.

Raises:
TypeError
If the index is not a DatetimeIndex.
529-2、参数

529-2-1、offset(必须)字符串,指定时间段的长度,offset字符串可以表示为不同的时间单位,比如'1D'(1天)、'2H'(2小时)、'30T'(30分钟)等,它表示希望从DataFrame的末尾获取的数据区间的时间长度。

529-3、功能

        根据指定的时间单位,返回DataFrame中最后一段时间的数据,该方法通常与时间索引的DataFrame一起使用,特别适用于具有时间序列数据的场景。

529-4、返回值

        返回一个新的DataFrame,其中包含从末尾开始的指定时间段内的数据,如果没有满足条件的行,则返回一个空的DataFrame。

529-5、说明

        无

529-6、用法
529-6-1、数据准备
529-6-2、代码示例
# 529、pandas.DataFrame.last方法
import pandas as pd
# 创建一个时间序列(日期范围缩小至7天以匹配数据长度)
date_rng = pd.date_range(start='2024-08-01', end='2024-08-07', freq='D')
# 创建一个与日期匹配的数据集
data = {
    'A': [1, 2, 3, 4, 5, 6, 7],
    'B': [7, 6, 5, 4, 3, 2, 1]
}
# 创建DataFrame,使用时间序列作为索引
df = pd.DataFrame(data, index=date_rng)
# 输出整个DataFrame
print("完整的DataFrame:")
print(df)
# 使用last()方法获取最后3天的数据
last_3_days = df.last('3D')
print("\n最后3天的数据:")
print(last_3_days)
# 使用last()方法获取最后5天的数据
last_5_days = df.last('5D')
print("\n最后5天的数据:")
print(last_5_days)
# 使用last()方法获取最后10天的数据
last_10_days = df.last('10D')
print("\n最后10天的数据(超出实际数据范围):")
print(last_10_days)
529-6-3、结果输出
# 529、pandas.DataFrame.last方法
# 完整的DataFrame:
#             A  B
# 2024-08-01  1  7
# 2024-08-02  2  6
# 2024-08-03  3  5
# 2024-08-04  4  4
# 2024-08-05  5  3
# 2024-08-06  6  2
# 2024-08-07  7  1
# 
# 最后3天的数据:
#             A  B
# 2024-08-05  5  3
# 2024-08-06  6  2
# 2024-08-07  7  1
# 
# 最后5天的数据:
#             A  B
# 2024-08-03  3  5
# 2024-08-04  4  4
# 2024-08-05  5  3
# 2024-08-06  6  2
# 2024-08-07  7  1
# 
# 最后10天的数据(超出实际数据范围):
#             A  B
# 2024-08-01  1  7
# 2024-08-02  2  6
# 2024-08-03  3  5
# 2024-08-04  4  4
# 2024-08-05  5  3
# 2024-08-06  6  2
# 2024-08-07  7  1
530、pandas.DataFrame.reindex方法
530-1、语法
# 530、pandas.DataFrame.reindex方法
pandas.DataFrame.reindex(labels=None, *, index=None, columns=None, axis=None, method=None, copy=None, level=None, fill_value=nan, limit=None, tolerance=None)
Conform DataFrame to new index with optional filling logic.

Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False.

Parameters:
labelsarray-like, optional
New labels / index to conform the axis specified by ‘axis’ to.

indexarray-like, optional
New labels for the index. Preferably an Index object to avoid duplicating data.

columnsarray-like, optional
New labels for the columns. Preferably an Index object to avoid duplicating data.

axisint or str, optional
Axis to target. Can be either the axis name (‘index’, ‘columns’) or number (0, 1).

method{None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}
Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index.

None (default): don’t fill gaps

pad / ffill: Propagate last valid observation forward to next valid.

backfill / bfill: Use next valid observation to fill gap.

nearest: Use nearest valid observations to fill gap.

copybool, default True
Return a new object, even if the passed indexes are the same.

Note

The copy keyword will change behavior in pandas 3.0. Copy-on-Write will be enabled by default, which means that all methods with a copy keyword will use a lazy copy mechanism to defer the copy and ignore the copy keyword. The copy keyword will be removed in a future version of pandas.

You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True

levelint or name
Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_valuescalar, default np.nan
Value to use for missing values. Defaults to NaN, but can be any “compatible” value.

limitint, default None
Maximum number of consecutive elements to forward or backward fill.

toleranceoptional
Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation abs(index[indexer] - target) <= tolerance.

Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type.

Returns:
DataFrame with changed index.
530-2、参数

530-2-1、labels(可选,默认值为None)指要重新索引的标签,该参数一般不直接使用,而是通过index或columns参数使用。

530-2-2、index(可选,默认值为None)指新的索引标签,如果提供了这个参数,DataFrame的行索引将按照这个参数进行重新排列;如果某个索引在原DataFrame中不存在,那么会填充NaN(可通过fill_value指定填充值)。

530-2-3、columns(可选,默认值为None)指新的列标签,与index类似,用于重新排列DataFrame的列索引;如果某个列标签在原DataFrame中不存在,也会填充NaN。

530-2-4、axis(可选,默认值为None){0 or 'index', 1 or 'columns'},指定重新索引的轴,如果指定为1,则是按照列索引进行重新排列。

530-2-5、method(可选,默认值为None){None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'},用于填充缺失标签的数据插值方法,可选值:

  • 'backfill'或'bfill':使用向前填充数据
  • 'pad'或'ffill':使用向后填充数据
  • 'nearest':使用最近的值进行填充

530-2-6、copy(可选,默认值为None)布尔值,如果为False,尝试避免对数据进行复制。默认会进行复制,除非新索引与旧索引完全一致且没有其他改变。

530-2-7、level(可选,默认值为None)整数或字符串,只在多重索引(MultiIndex)DataFrame中适用,指定重新索引的是哪一个级别。

530-2-8、fill_value(可选,默认值为nan)用于填补重新索引后缺失值的标量值。

530-2-9、limit(可选,默认值为None)整数,填充时的最大步数限制,该参数结合method一起使用。

530-2-10、tolerance(可选,默认值为None)用于限制填充过程中允许的最大距离,需要与method='nearest'组合使用。

530-3、功能

        根据给定的index和columns参数重新排列索引和列,如果新的索引或列在原DataFrame中不存在,这些位置将被填充NaN或指定的fill_value。

530-4、返回值

        返回值是一个新的DataFrame,新的DataFrame根据指定的索引和列进行了重新排列,可能会包含一些填充值(例如NaN或者用户指定的fill_value),以填补新的索引或列在原始DataFrame中不存在的位置。

530-5、说明

        无

530-6、用法
530-6-1、数据准备
530-6-2、代码示例
# 530、pandas.DataFrame.reindex方法
import pandas as pd
# 创建一个示例DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
}, index=['a', 'b', 'c'])
print("原始DataFrame:")
print(df)
# 重新按照新的索引重新排列DataFrame
new_index = ['a', 'c', 'd']
new_columns = ['A', 'C']
df_reindexed = df.reindex(index=new_index, columns=new_columns, fill_value=0)
print("\n重新索引后的DataFrame:")
print(df_reindexed)
530-6-3、结果输出
# 530、pandas.DataFrame.reindex方法
# 原始DataFrame:
#    A  B
# a  1  4
# b  2  5
# c  3  6
# 
# 重新索引后的DataFrame:
#    A  C
# a  1  0
# c  3  0
# d  0  0

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2141586.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言刷题日记(附详解)(5)

一、选填部分 第一题: 下面代码在64位系统下的输出为( ) void print_array(int arr[]) {int n sizeof(arr) / sizeof(arr[0]);for (int i 0; i < n; i)printf("%d", arr[i]); } int main() {int arr[] { 1,2,3,4,5 };print_array(arr);return 0; } A . 1…

vi | vim基本使用

vim三模式&#xff1a;① 输入模式 ②命令模式 ③末行模式&#xff08;编辑模式&#xff09; vim四模式&#xff1a;① 输入模式 ②命令模式 ③末行模式&#xff08;编辑模式&#xff09; ④V模式 一、命令模式进入输入模式方法&#xff1a; 二、命令模式基…

Hybrid接口的基础配置

Hybrid模式是交换机端口的一种配置模式&#xff0c;它允许端口同时携带多个VLAN&#xff08;虚拟局域网&#xff09;的流量。Hybrid端口可以指定哪些VLAN的数据帧被打上标签&#xff08;tagged&#xff09;和哪些VLAN的数据帧在发送时去除标签&#xff08;untagged&#xff09;…

828华为云征文|部署知识库问答系统 MaxKB

828华为云征文&#xff5c;部署知识库问答系统 MaxKB 一、Flexus云服务器X实例介绍1.1 云服务器介绍1.2 核心竞争力1.3 计费模式 二、Flexus云服务器X实例配置2.1 重置密码2.2 服务器连接2.3 安全组配置 三、部署 MaxKB3.1 MaxKB 介绍3.2 Docker 环境搭建3.3 MaxKB 部署3.4 Max…

Leetcode—322. 零钱兑换【中等】(memset(dp,0x3f, sizeof(dp))

2024每日刷题&#xff08;159&#xff09; Leetcode—322. 零钱兑换 算法思想 dp实现代码 class Solution { public:int coinChange(vector<int>& coins, int amount) {int m coins.size();int n amount;int dp[m 1][n 1];memset(dp, 0x3f, sizeof(dp));dp[0][…

基于springboot+vue+uniapp的驾校报名小程序

开发语言&#xff1a;Java框架&#xff1a;springbootuniappJDK版本&#xff1a;JDK1.8服务器&#xff1a;tomcat7数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/ideaMaven包&#…

使用随机森林模型在digits数据集上执行分类任务

程序功能 使用随机森林模型对digits数据集进行手写数字分类任务。具体步骤如下&#xff1a; 加载数据&#xff1a;从digits数据集中获取手写数字图片的特征和对应的标签。 划分数据&#xff1a;将数据集分为训练集和测试集&#xff0c;测试集占30%。 训练模型&#xff1a;使用…

鸿蒙开发笔记_电商严选02_登录页面跳转到我的页面、并传值

鸿蒙开发笔记整理,方便以后查阅! 由于上班较忙,只能抽空闲暇时间,快速整理更新中。。。 登录页面跳转到我的页面、并传值 效果图 我的设置页面 /*** 我的设置页面*/ import CommonConstants from ./CommonConstants import ItemData from ./ItemData import DataModel fr…

某个图形商标驳回,不建议做驳回复审!

近日一四川的网友联系到普推知产商标老杨&#xff0c;咨询看驳回的商标可以做驳回复审不&#xff0c;是个纯图形商标&#xff0c;这个一看是一标多类&#xff0c;就是在一个商标名称是申请两个类别&#xff0c;42类部分通过&#xff0c;35类全部驳回。 35类和42类引用的近似商标…

07_Python数据类型_集合

Python的基础数据类型 数值类型&#xff1a;整数、浮点数、复数、布尔字符串容器类型&#xff1a;列表、元祖、字典、集合 集合 集合&#xff08;set&#xff09;是Python中一个非常强大的数据类型&#xff0c;它存储的是一组无序且不重复的元素&#xff0c;集合中的元素必须…

SpringBoot 消息队列RabbitMQ死信交换机

介绍 生产者发送消息时指定一个时间&#xff0c;消费者不会立刻收到消息&#xff0c;而是在指定时间之后才收到消息。 死信交换机 当一个队列中的消息满足下列情况之一时&#xff0c;就会成为死信(dead letter) 消费者使用basic.reject或 basic.nack声明消费失败&#xff0…

LidarView之定制版本

介绍 LidarView软件定制开发需要关注几点&#xff1a;1.应用程序名称&#xff1b;2.程序logo&#xff1b;3.Application版本号&#xff1b;4.安装包版本号 应用程序名称 在项目的顶层cmake里边可以指定程序名称 project(LidarView)需要指定跟Superbuild一样的编译类型 set…

英语学习之fruit

目录 不熟悉熟悉 不熟悉 breadfruit 面包果 date 椰枣 raspberry 覆盆子 blackberry 黑莓 blackcurrant 黑加仑&#xff0c;黑醋栗 plum 李子 熟悉 apple 苹果&#x1f34e; coconut 椰子&#x1f965; banana 香蕉&#x1f34c; tomato 西红柿 pear 梨子 watermelon 西瓜…

30款免费好用的工具,打工人必备!

免费工具软件&#xff0c;办公人必备&#xff0c;提升工作效率 启动盘制作&#xff1a;Ventoype工具&#xff1a;微PEwindows/office jh工具&#xff1a;HEU KMS Activator桌面资料转移工具&#xff1a;个人资料专业工具右键菜单管理&#xff1a;ContextMenuManager驱动安装&a…

【面试八股总结】GMP模型

GMP概念 G&#xff08;Goroutine&#xff09;&#xff1a;代表Go协程&#xff0c;是参与调度与执行的最小单位。 存储Goroutine执行栈信息、状态、以及任务函数等。G的数量无限制&#xff0c;理论上只受内存的影响。Goroutines 是并发执行的基本单位&#xff0c;相比于传统的线…

虽难必学系列:Netty

Netty 是一个基于 Java 的高性能、异步事件驱动的网络应用框架&#xff0c;广泛用于构建各类网络应用&#xff0c;尤其是在高并发、低延迟场景下表现出色。作为一个开源项目&#xff0c;Netty 提供了丰富的功能&#xff0c;使得开发者可以轻松构建协议服务器和客户端应用程序。…

Nginx从入门到入土(一):DNS域名解析

前言 hostName&#xff0c;在Linux系统上是一个命令&#xff0c;用来显示和设置系统的主机名称。其实它就是域名。 常见的域名有我们熟悉的taobao.com;baidu.com等等。 我们在地址栏输入baidu.com 进入的就是此页面。我们看到地址栏里显示的是www.baidu.com 。 注意&#xf…

MySQL篇(运算符)(持续更新迭代)

目录 一、简介 二、运算符使用 1. 算术运算符 1.1. 加法运算符 1.2. 减法运算符 1.3. 乘法与除法运算符 1.4. 求模&#xff08;求余&#xff09;运算符 2. 比较运算符 2.1. 等号运算符 2.2. 安全等于运算符 2.3. 不等于运算符 2.4. 空运算符 2.5. 非空运算符 2.6.…

Java数据存储结构——平衡二叉树

文章目录 22.1.3 平衡二叉树22.1.3.1 LL22.1.3.2 LR22.1.3.3 RR22.1.3.4 RL 22.1.3 平衡二叉树 平衡二叉树的特点&#xff1a; 二叉树左右两个子树的高度差不超过1任意节点的左右两个子树都是一颗平衡二叉树 在原来的平衡二叉树中&#xff0c;新增数据会破坏平衡性&#xff…

Linux per memcg lru lock

内核关于per memcg lru lock的重要提交&#xff1a; f9b1038ebccad354256cf84749cbc321b5347497 6168d0da2b479ce25a4647de194045de1bdd1f1d 背景 自电子计算机诞生以来&#xff0c;内存性能一直是行业关心的重点。内存也随着摩尔定律&#xff0c;在大小和速度上一直增长。云…