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

目录

一、用法精讲

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、结果输出

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、结果输出

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、结果输出

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、结果输出

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、博客个人主页

一、用法精讲

241、pandas.Series.view方法
241-1、语法
# 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、数据准备
241-6-2、代码示例
# 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、结果输出
# 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
242、pandas.Series.compare方法
242-1、语法
# 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、数据准备
242-6-2、代码示例
# 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、结果输出
# 242、pandas.Series.compare方法
# Comparison result:
#    self  other
# 0   5.0    3.0
# 1  11.0    6.0
# 3   8.0   24.0
243、pandas.Series.update方法
243-1、语法
# 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、数据准备
243-6-2、代码示例
# 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、结果输出
# 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)
244、pandas.Series.asfreq方法
244-1、语法
# 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、数据准备
244-6-2、代码示例
# 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、结果输出
# 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
245、pandas.Series.asof方法
245-1、语法
# 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 DataFrame

Parameters:
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 scalar

Series: when self is a Series and where is an array-like, or when self is a DataFrame and where is a scalar

DataFrame : 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、数据准备
245-6-2、代码示例
# 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、结果输出
# 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、博客个人主页
  • 73
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 81
    评论
评论 81
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神奇夜光杯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值