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

目录

一、用法精讲

pandas.DataFrame.to_csv%E5%87%BD%E6%95%B0-toc" style="margin-left:120px;">241、pandas.Series.view方法

241-1、语法

241-2、参数

241-3、功能

241-4、返回值

241-5、说明

241-6、用法

241-6-1、数据准备

241-6-2、代码示例

241-6-3、结果输出

pandas.Series.compare%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">242、pandas.Series.compare方法

242-1、语法

242-2、参数

242-3、功能

242-4、返回值

242-5、说明

242-6、用法

242-6-1、数据准备

242-6-2、代码示例

242-6-3、结果输出

pandas.Series.update%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">243、pandas.Series.update方法

243-1、语法

243-2、参数

243-3、功能

243-4、返回值

243-5、说明

243-6、用法

243-6-1、数据准备

243-6-2、代码示例

243-6-3、结果输出

pandas.Series.asfreq%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">244、pandas.Series.asfreq方法

244-1、语法

244-2、参数

244-3、功能

244-4、返回值

244-5、说明

244-6、用法

244-6-1、数据准备

244-6-2、代码示例

244-6-3、结果输出

pandas.Series.asof%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">245、pandas.Series.asof方法

245-1、语法

245-2、参数

245-3、功能

245-4、返回值

245-5、说明

245-6、用法

245-6-1、数据准备

245-6-2、代码示例

245-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

pandas.DataFrame.to_csv%E5%87%BD%E6%95%B0">241、pandas.Series.view方法
241-1、语法
python"># 241、pandas.Series.view方法
pandas.Series.view(dtype=None)
Create a new view of the Series.Deprecated since version 2.2.0: Series.view is deprecated and will be removed in a future version. Use Series.astype() as an alternative to change the dtype.This function will return a new Series with a view of the same underlying values in memory, optionally reinterpreted with a new data type. The new data type must preserve the same size in bytes as to not cause index misalignment.Parameters:
dtype
data type
Data type object or one of their string representations.Returns:
Series
A new Series object as a view of the same data in memory.
241-2、参数

241-2-1、dtype(可选,默认值为None)数据类型,可以是NumPy数据类型或pandas数据类型。如果未指定,返回相同dtype的视图。

241-3、功能

        用于创建Series的视图,并且可以通过指定不同的数据类型来查看同一数据在内存中的不同表示,这在数据转换和内存管理方面非常有用。

241-4、返回值

        返回的视图是一个新的Series对象,但它与原始Series共享同一块内存,因此对视图所做的修改会直接影响原始Series。

241-5、说明

        此方法目前仍然能用,但后续将被pandas.Series.astype方法所替代。

241-6、用法
241-6-1、数据准备
python">无
241-6-2、代码示例
python"># 241、pandas.Series.view方法
# 241-1、创建一个视图并查看不同的数据类型表示
import pandas as pd
# 创建一个Series
s = pd.Series([1, 2, 3, 4])
# 以float64数据类型查看Series
view_as_float = s.view(dtype='float64')
print("Original Series:")
print(s)
print("Viewed as float64:")
print(view_as_float, end='\n\n')# 241-2、修改视图中的数据,影响原始Series
import pandas as pd
# 创建一个Series
s_original = pd.Series([1, 2, 3, 4])
# 创建一个视图
s_view = s_original.view()
# 修改视图中的数据
s_view[0] = 10
print("Original Series after modification:")
print(s_original)
print("Modified view:")
print(s_view)
241-6-3、结果输出
python"># 241、pandas.Series.view方法
# 241-1、创建一个视图并查看不同的数据类型表示
# Original Series:
# 0    1
# 1    2
# 2    3
# 3    4
# dtype: int64
# Viewed as float64:
# 0    4.940656e-324
# 1    9.881313e-324
# 2    1.482197e-323
# 3    1.976263e-323
# dtype: float64# 241-2、修改视图中的数据,影响原始Series
# Original Series after modification:
# 0    10
# 1     2
# 2     3
# 3     4
# dtype: int64
# Modified view:
# 0    10
# 1     2
# 2     3
# 3     4
# dtype: int64
pandas.Series.compare%E6%96%B9%E6%B3%95">242、pandas.Series.compare方法
242-1、语法
python"># 242、pandas.Series.compare方法
pandas.Series.compare(other, align_axis=1, keep_shape=False, keep_equal=False, result_names=('self', 'other'))
Compare to another Series and show the differences.Parameters:
otherSeries
Object to compare with.align_axis{0 or ‘index’, 1 or ‘columns’}, default 1
Determine which axis to align the comparison on.0, or ‘index’Resulting differences are stacked vertically
with rows drawn alternately from self and other.1, or ‘columns’Resulting differences are aligned horizontally
with columns drawn alternately from self and other.keep_shapebool, default False
If true, all rows and columns are kept. Otherwise, only the ones with different values are kept.keep_equalbool, default False
If true, the result keeps values that are equal. Otherwise, equal values are shown as NaNs.result_namestuple, default (‘self’, ‘other’)
Set the dataframes names in the comparison.New in version 1.5.0.Returns:
Series or DataFrame
If axis is 0 or ‘index’ the result will be a Series. The resulting index will be a MultiIndex with ‘self’ and ‘other’ stacked alternately at the inner level.If axis is 1 or ‘columns’ the result will be a DataFrame. It will have two columns namely ‘self’ and ‘other’.
242-2、参数

242-2-1、other(必须)表示另一个与当前Series进行比较的Series。

242-2-2、align_axis(可选,默认值为1)表示对齐轴,可选0或1:1表示列对齐,0表示行对齐。

242-2-3、keep_shape(可选,默认值为False)是否保留原始的Series形状,如果为True,则保留NaN值。

242-2-4、keep_equal(可选,默认值为False)是否在结果中保留相等的元素,如果为True,相等的元素也会显示在结果中。

242-2-5、result_names(可选,默认值为('self', 'other'))表示结果中显示的列名。

242-3、功能

        用于对比两个Series对象,找出不同之处。

242-4、返回值

        返回一个DataFrame,其中包含两个Series对比后的差异部分。

242-5、说明

        无

242-6、用法
242-6-1、数据准备
python">无
242-6-2、代码示例
python"># 242、pandas.Series.compare方法
import pandas as pd
# 创建两个Series
s1 = pd.Series([5, 11, 10, 8])
s2 = pd.Series([3, 6, 10, 24])
# 对比两个Series
result = s1.compare(s2)
print("Comparison result:")
print(result, end='\n\n')
242-6-3、结果输出
python"># 242、pandas.Series.compare方法
# Comparison result:
#    self  other
# 0   5.0    3.0
# 1  11.0    6.0
# 3   8.0   24.0
pandas.Series.update%E6%96%B9%E6%B3%95">243、pandas.Series.update方法
243-1、语法
python"># 243、pandas.Series.update方法
pandas.Series.update(other)
Modify Series in place using values from passed Series.Uses non-NA values from passed Series to make updates. Aligns on index.Parameters:
other
Series, or object coercible into Series
243-2、参数

243-2-1、other(必须)表示另一个Series或DataFrame,用于更新当前Series的值,如果other是DataFrame,必须和当前Series具有相同的索引。

243-3、功能

        用于使用另一个Series的值来更新当前Series的值,它直接修改原Series,并且不返回新的对象。

243-4、返回值

        没有返回值,它是一个inplace操作,这意味着它会直接修改调用该方法的Series对象,而不是返回一个新的Series。

243-5、说明

        无

243-6、用法
243-6-1、数据准备
python">无
243-6-2、代码示例
python"># 243、pandas.Series.update方法
# 243-1、基本更新
import pandas as pd
# 创建两个Series
s1 = pd.Series({'a': 3, 'b': 6, 'c': 10, 'd': 24})
s2 = pd.Series({'b': 5, 'd': 11, 'e': 10, 'f': 8})
# 使用s2更新s1
s1.update(s2)
print("Updated Series:")
print(s1, end='\n\n')# 243-2、带有NaN值的更新
import pandas as pd
# 创建两个Series,其中包含NaN值
s3 = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': None})
s4 = pd.Series({'b': 20, 'd': None, 'e': 50})
# 使用s4更新s3
s3.update(s4)
print("Updated Series with NaN values:")
print(s3)
243-6-3、结果输出
python"># 243、pandas.Series.update方法
# 243-1、基本更新
import pandas as pd
# 创建两个Series
s1 = pd.Series({'a': 3, 'b': 6, 'c': 10, 'd': 24})
s2 = pd.Series({'b': 5, 'd': 11, 'e': 10, 'f': 8})
# 使用s2更新s1
s1.update(s2)
print("Updated Series:")
print(s1, end='\n\n')# 243-2、带有NaN值的更新
import pandas as pd
# 创建两个Series,其中包含NaN值
s3 = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': None})
s4 = pd.Series({'b': 20, 'd': None, 'e': 50})
# 使用s4更新s3
s3.update(s4)
print("Updated Series with NaN values:")
print(s3)
pandas.Series.asfreq%E6%96%B9%E6%B3%95">244、pandas.Series.asfreq方法
244-1、语法
python"># 244、pandas.Series.asfreq方法
pandas.Series.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)
Convert time series to specified frequency.Returns the original data conformed to a new index with the specified frequency.If the index of this Series/DataFrame is a PeriodIndex, the new index is the result of transforming the original index with PeriodIndex.asfreq (so the original index will map one-to-one to the new index).Otherwise, the new index will be equivalent to pd.date_range(start, end, freq=freq) where start and end are, respectively, the first and last entries in the original index (see pandas.date_range()). The values corresponding to any timesteps in the new index which were not present in the original index will be null (NaN), unless a method for filling such unknowns is provided (see the method parameter below).The resample() method is more appropriate if an operation on each group of timesteps (such as an aggregate) is necessary to represent the data at the new frequency.Parameters:
freq
DateOffset or str
Frequency DateOffset or string.method
{‘backfill’/’bfill’, ‘pad’/’ffill’}, default None
Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present):‘pad’ / ‘ffill’: propagate last valid observation forward to next valid‘backfill’ / ‘bfill’: use NEXT valid observation to fill.how
{‘start’, ‘end’}, default end
For PeriodIndex only (see PeriodIndex.asfreq).normalize
bool, default False
Whether to reset output index to midnight.fill_value
scalar, optional
Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present).Returns:
Series/DataFrame
Series/DataFrame object reindexed to the specified frequency.
244-2、参数

244-2-1、freq(必须)字符串或DataOffset对象,表示指定目标频率,常见的频率字符串包括:

  • 'D': 每日
  • 'M': 每月
  • 'A': 每年
  • 'H': 每小时
  • 'T'或'min': 每分钟
  • 'S': 每秒

244-2-2、method(可选,默认值为None)字符串('pad','ffill','backfill','bfill')或None指定当重新采样时如何填充缺失的值。

  • 'pad'或'ffill':用前一个有效值填充缺失值。
  • 'backfill'或'bfill':用下一个有效值填充缺失值。

244-2-3、how(可选,默认值为None)字符串,在较新的版本中已经被移除,可以忽略此参数。

244-2-4、normalize(可选,默认值为False)布尔值,如果为True,则将时间戳规范化到午夜时间。

244-2-5、fill_value(可选,默认值为None)标量值,指定用于填充缺失值的标量值。

244-3、功能

        用于将时间序列重新采样为指定的频率,可能会填充或不填充缺失值,具体取决于method和fill_value参数。

244-4、返回值

        返回一个新的Series,其索引为指定频率的时间戳,数据根据指定的填充方法处理。

244-5、说明

        无

244-6、用法
244-6-1、数据准备
python">无
244-6-2、代码示例
python"># 244、pandas.Series.asfreq方法
import pandas as pd
# 创建一个时间序列
rng = pd.date_range('2024-01-01', periods=6, freq='2D')
ts = pd.Series(range(6), index=rng)
# 将时间序列转换为每日频率,使用前向填充方法
ts_daily_ffill = ts.asfreq('D', method='ffill')
# 将时间序列转换为每日频率,不填充缺失值
ts_daily_no_fill = ts.asfreq('D')
# 将时间序列转换为每日频率,填充缺失值为0
ts_daily_fill_value = ts.asfreq('D', fill_value=0)
print("原始时间序列:")
print(ts)
print("\n转换为每日频率,使用前向填充方法:")
print(ts_daily_ffill)
print("\n转换为每日频率,不填充缺失值:")
print(ts_daily_no_fill)
print("\n转换为每日频率,填充缺失值为0:")
print(ts_daily_fill_value)
244-6-3、结果输出
python"># 244、pandas.Series.asfreq方法
# 原始时间序列:
# 2024-01-01    0
# 2024-01-03    1
# 2024-01-05    2
# 2024-01-07    3
# 2024-01-09    4
# 2024-01-11    5
# Freq: 2D, dtype: int64
# 
# 转换为每日频率,使用前向填充方法:
# 2024-01-01    0
# 2024-01-02    0
# 2024-01-03    1
# 2024-01-04    1
# 2024-01-05    2
# 2024-01-06    2
# 2024-01-07    3
# 2024-01-08    3
# 2024-01-09    4
# 2024-01-10    4
# 2024-01-11    5
# Freq: D, dtype: int64
# 
# 转换为每日频率,不填充缺失值:
# 2024-01-01    0.0
# 2024-01-02    NaN
# 2024-01-03    1.0
# 2024-01-04    NaN
# 2024-01-05    2.0
# 2024-01-06    NaN
# 2024-01-07    3.0
# 2024-01-08    NaN
# 2024-01-09    4.0
# 2024-01-10    NaN
# 2024-01-11    5.0
# Freq: D, dtype: float64
# 
# 转换为每日频率,填充缺失值为0:
# 2024-01-01    0
# 2024-01-02    0
# 2024-01-03    1
# 2024-01-04    0
# 2024-01-05    2
# 2024-01-06    0
# 2024-01-07    3
# 2024-01-08    0
# 2024-01-09    4
# 2024-01-10    0
# 2024-01-11    5
# Freq: D, dtype: int64
pandas.Series.asof%E6%96%B9%E6%B3%95">245、pandas.Series.asof方法
245-1、语法
python"># 245、pandas.Series.asof方法
pandas.Series.asof(where, subset=None)
Return the last row(s) without any NaNs before where.The last row (for each element in where, if list) without any NaN is taken. In case of a DataFrame, the last row without NaN considering only the subset of columns (if not None)If there is no good value, NaN is returned for a Series or a Series of NaN values for a DataFrameParameters:
wheredate or array-like of dates
Date(s) before which the last row(s) are returned.subsetstr or array-like of str, default None
For DataFrame, if not None, only use these columns to check for NaNs.Returns:
scalar, Series, or DataFrame
The return can be:scalar : when self is a Series and where is a scalarSeries: when self is a Series and where is an array-like, or when self is a DataFrame and where is a scalarDataFrame : when self is a DataFrame and where is an array-like
245-2、参数

245-2-1、where(必须)单个索引值或索引值的列表,指定要查找的索引位置,如果是单个索引值,则返回该位置之前的最新有效值;如果是索引值的列表,则对每个索引值执行查找操作。

245-2-2、subset(可选,默认值为None)列名或列名的列表(仅用于DataFrame),指定在DataFrame中应用查找操作的列,如果未指定,则默认使用所有列。

245-3、功能

        用于返回给定索引位置之前(或恰好在该位置)的最新有效值,它在处理时间序列数据时特别有用。

245-4、返回值

        返回给定索引位置之前的最新有效值,对于单个索引值,返回一个标量值;对于索引值的列表,返回一个包含查找结果的Series

245-5、说明

        无

245-6、用法
245-6-1、数据准备
python">无
245-6-2、代码示例
python"># 245、pandas.Series.asof方法
import pandas as pd
import numpy as np
# 创建一个包含缺失值的时间序列
dates = pd.date_range('2024-01-01', periods=10, freq='D')
values = [np.nan, 1.2, np.nan, 3.4, np.nan, np.nan, 7.8, np.nan, 9.0, np.nan]
ts = pd.Series(values, index=dates)
# 使用asof方法找到指定日期之前的最新有效值
print(ts.asof('2024-01-05'))
# 使用asof方法填充缺失值
filled_ts = ts.copy()
filled_ts = filled_ts.fillna(method='ffill')
print(filled_ts)
245-6-3、结果输出
python"># 245、pandas.Series.asof方法
# 3.4
# 2024-01-01    NaN
# 2024-01-02    1.2
# 2024-01-03    1.2
# 2024-01-04    3.4
# 2024-01-05    3.4
# 2024-01-06    3.4
# 2024-01-07    7.8
# 2024-01-08    7.8
# 2024-01-09    9.0
# 2024-01-10    9.0
# Freq: D, dtype: float64

二、推荐阅读

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

http://www.ppmy.cn/news/1504303.html

相关文章

20240731软考架构------软考6-10答案解析

每日打卡题6-10答案 6、【2012年真题】 难度:一般 若系统中的某子模块需要为其他模块提供访问不同数据库系统的功能,这些数据库系统提供的访问接口有一定的差异,但访问过程却都是相同的,例如,先连接数据库&#xff0c…

docker安装与container基本使用

安装 Homebrew 的 Cask 已经支持 Docker for Mac, mac用户狂喜 brew install --cask --appdir/Applications docker其他入门用法可参考 Docker Hello World- 菜鸟教程 或网上自行搜索博客学习。本文主要记录我运行go-zero-mall用到的一些注意点。当然,gonivinck项…

SolidEdge二次开发(C#)-环境配置

文章目录 1、前言2、环境配置2.1 安装Solidworks20242.2 安装VS20222.3 查看Com组件2.3.1 在VS2022中创建一个wpf工程项目2.3.2 添加com组件 1、前言 SolidEdge是Siemens PLM Software公司旗下的三维CAD软件,采用Siemens PLM Software公司自己拥有专利的Parasolid作…

宝塔面板上,安装rabbitmq

废话不多说,直接上干货! 第一步:登录宝塔账号,在软件商店里搜索 第二步:点击设置 第三步:已经完成了,还看啥!

Agent类型解析:AIGC在不同领域的应用与影响

目录 引言 垂直智能体(Vertical Agent) 水平智能体(Horizontal Agent) 混合智能体(Hybrid Agent) 结论 引言 在人工智能(AI)领域,智能体(Agent&#xf…

Spring统一返回类型中关于String的问题

文章目录 1. 问题铺垫2. 解决方法3. 问题分析4 解决方法解释 1. 问题铺垫 首先设置了以下代码统一处理返回类型 ControllerAdvice public class ResponseAdvice implements ResponseBodyAdvice {Overridepublic boolean supports(MethodParameter returnType, Class converte…

SpringCloud入门学习笔记(四)

Sentinel篇 SpringCloud入门学习笔记(一)-CSDN博客 SpringCloud入门学习笔记(二)-CSDN博客 SpringCloud入门学习笔记(三)-CSDN博客 前言 在互联网应用过程中,有很多的高并发访问场景&#…

【Rust练习】6.所有权

练习题来自:https://practice-zh.course.rs/ownership/ownership.html 1 fn main() {// 使用尽可能多的方法来通过编译let x String::from("hello, world");let y x;println!("{},{}",x,y); }这是最典型的所有权转移的错误,x拥有…

修改VSCode插件默认安装路径

文章目录 前言VSCode插件默认安装路径添加环境变量先修改路径注意事项 前言 今天发现C盘快满了,只能清理点东西,给C盘腾出的空间出来,结果一看,VSCode的插件目录就占了不少呢。 VSCode插件默认安装路径 C:\Users\{个人用户名}\.…

推荐Nodejs下高效存储树到数据库工具库-FlexTree

官网 | English FlexTree是Nodejs下一个基于左右值算法的树结构库,它提供了一种简单的方式来存储和操作树形结构数据。 FlexTree提供了简单而丰富的API让你可以轻松的操作树,如增删改查、遍历、移动、查询等。 主要特性: 基于左右值算法&a…

HTML+CSS+JavaScript制作七夕表白网页(含音乐+自定义文字+烟花特效)

利用HTMLCSSJavaScript制作了一个简单的七夕表白网页: 这是一个简单的表白功能,可以用于小哥哥小姐姐在情人节向心爱的人表白使用点击信封中间的爱心,会出现一封信由信封向外展开,与此同时会有烟花绽放,并且自动播放背…

Python面试题:结合Python技术,详细讲解如何使用Pexpect自动化交互命令行工具

Pexpect 是一个用于自动化交互式命令行工具的 Python 库。它可以模拟用户与命令行程序的交互,从而在脚本中自动化执行这些命令。以下是如何使用 Pexpect 自动化命令行工具的详细步骤: 1. 安装 Pexpect 首先,你需要安装 Pexpect 库。可以通过…

地理科学专业| 中国大学排行榜(2024年)

地理科学专业| 中国大学排行榜(2024年) 原文链接

构建高效的团队协作:Git工作流和代码审查

引言 在软件开发过程中,高效的团队协作是保证项目成功的关键因素之一。Git作为当前最流行的版本控制系统,提供了强大的分支管理和合并功能,而代码审查则是确保代码质量和项目进度的重要环节。本文将分享高效的Git工作流程和代码审查实践&…

模型训练时,模型输出nan

在模型训练过程中,模型输出 NaN(Not a Number)通常是由数值不稳定导致的。这可能是由于多种因素造成的,包括但不限于: 学习率过高:过大的学习率可能导致权重更新过大,使得权重变得非常大或非常…

Windows上安装EMQX作为MQTT服务器以及配置MQTTX客户端

一、安装EMQX MQTT服务器 EMQX 是一个高性能、可扩展的物联网消息中间件,EMQX 实现了 MQTT 协议的服务器端,即 MQTT Broker,它负责接收来自客户端的连接请求,处理订阅、发布消息,并将消息转发给相应的订阅者。 下载E…

电脑出现连接不上网络,远程计算机不接受连接的解决方法

第一步:打开Cmd,输入inetcpl.cpl inetcpl.cpl 第二步:点击“连接” 第三步:点击局域网设置 第四步:三个都不选,点击确定 之后网络就可以正常访问了!

【已解决】关于MyBatis的collection集合中只能取到一条数据的问题

一、问题 在涉及多表查询的时候,使用collection元素来映射集合属性时,出现了只能查询到一条数据的情况,但用sql语句在数据库中查询会有多条记录。 二、原因 如果两表联查,主表和明细表的主键都是id的话,明细表的多条…

浏览器用户文件夹详解 - Top Sites(七)

1. TopSites简介 1.1 什么是TopSites文件? TopSites文件是Chromium浏览器中用于存储用户访问频率最高的网站信息的一个重要文件。每当用户在浏览器中访问网站时,这些信息都会被记录在TopSites文件中。通过这些记录,浏览器可以为用户提供个性…

Linux初学基本命令

linux文件目录 1、bin->usr/bin binary存放命令 所有账户可以使用 Linux可以执行的文件,我们称之为命令command 2、boot 存放系统启动文件 3、dev device存放设备文件 4、etc 存放配置文件的目录 configration files 5、home home家目录 存…