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

目录

一、用法精讲

96、pandas.Series.bool属性

96-1、语法

96-2、参数

96-3、功能

96-4、返回值

96-5、说明

96-6、用法

96-6-1、数据准备

96-6-2、代码示例

96-6-3、结果输出

97、pandas.Series.to_numpy方法

97-1、语法

97-2、参数

97-3、功能

97-4、返回值

97-5、说明

97-6、用法

97-6-1、数据准备

97-6-2、代码示例

97-6-3、结果输出

98、pandas.Series.to_period方法

98-1、语法

98-2、参数

98-3、功能

98-4、返回值

98-5、说明

98-6、用法

98-6-1、数据准备

98-6-2、代码示例

98-6-3、结果输出

99、pandas.Series.to_timestamp方法

99-1、语法

99-2、参数

99-3、功能

99-4、返回值

99-5、说明

99-6、用法

99-6-1、数据准备

99-6-2、代码示例

99-6-3、结果输出

100、pandas.Series.to_list方法

100-1、语法

100-2、参数

100-3、功能

100-4、返回值

100-5、说明

100-6、用法

100-6-1、数据准备

100-6-2、代码示例

100-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

96、pandas.Series.bool属性
96-1、语法
# 96、pandas.Series.bool属性
pandas.Series.bool()
Return the bool of a single element Series or DataFrame.

Deprecated since version 2.1.0: bool is deprecated and will be removed in future version of pandas. For Series use pandas.Series.item.

This must be a boolean scalar value, either True or False. It will raise a ValueError if the Series or DataFrame does not have exactly 1 element, or that element is not boolean (integer values 0 and 1 will also raise an exception).

Returns:
bool
The value in the Series or DataFrame.
96-2、参数

        无

96-3、功能

        用于将pandas.Series中的唯一元素转换为布尔值。

96-4、返回值

        返回一个布尔值,若Series对象的唯一元素为True,则返回True;反之,则返回False。

96-5、说明

        使用bool()来强制转换Series对象为布尔值,前提是Series对象中只能有一个元素。

96-6、用法
96-6-1、数据准备
96-6-2、代码示例
# 96、pandas.Series.bool属性
import pandas as pd
s = pd.Series([True])
print(s.bool())
s2 = pd.Series([False])
print(s2.bool())
96-6-3、结果输出
# 96、pandas.Series.bool属性
# True
# False
97、pandas.Series.to_numpy方法
97-1、语法
# 97、pandas.Series.to_numpy方法
pandas.Series.to_numpy(dtype=None, copy=False, na_value=_NoDefault.no_default, **kwargs)
A NumPy ndarray representing the values in this Series or Index.

Parameters:
dtype
str or numpy.dtype, optional
The dtype to pass to numpy.asarray().

copy
bool, default False
Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.

na_value
Any, optional
The value to use for missing values. The default value depends on dtype and the type of the array.

**kwargs
Additional keywords passed through to the to_numpy method of the underlying array (for extension arrays).

Returns:
numpy.ndarray
97-2、参数

97-2-1、dtype(可选,默认值为None)指定返回数组的数据类型。如果未提供,方法将使用Series的数据类型。

97-2-2、copy(可选,默认值为False)表示是否强制创建副本,如果为True,则强制创建一个新的数组副本;否则,如果可能,方法会返回原始数据的视图而不是副本。

97-2-3、na_value(可选)用于替换缺失值(NaN或None)的标量值,只有在dtype为对象类型时才有效。如果提供此参数,方法会用指定的标量值替换Series中的缺失值。

97-2-4、**kwargs(可选)其他额外的关键字参数,通常不会用到。

97-3、功能

        用于将Series对象中的数据提取出来,并转换为NumPy数组。

97-4、返回值

        返回值是一个NumPy数组(numpy.ndarray),它包含了Series中的数据。

97-5、说明

        返回值的特点:

97-5-1、数据类型: 数组的元素类型会根据Series的数据类型自动调整,除非你显式指定了dtype参数。例如,如果Series中包含整数,返回的NumPy数组也会是整数类型,除非你指定了不同的数据类型。

97-5-2、缺失值处理: 如果Series中有缺失值(NaN或None),并且没有指定na_value参数,返回的数组会保留这些缺失值。例如,缺失值会被表示为NaN或适当的NaN替代值,取决于数据类型。

97-5-3、副本与视图: 如果copy参数设置为True,返回的数组是Series数据的副本;如果copy参数为False,则返回的数组可能是原始数据的视图,这取决于数据的内存布局。

97-6、用法
97-6-1、数据准备
97-6-2、代码示例
# 97、pandas.Series.to_numpy方法
import pandas as pd
import numpy as np
# 创建一个Series对象
s = pd.Series([1, 2, np.nan, 4])
# 转换为NumPy数组
array = s.to_numpy()
print(array)
print(type(array))
97-6-3、结果输出
# 97、pandas.Series.to_numpy方法
# [ 1.  2. nan  4.]
# <class 'numpy.ndarray'>
98、pandas.Series.to_period方法
98-1、语法
# 98、pandas.Series.to_period方法
pandas.Series.to_period(freq=None, copy=None)
Convert Series from DatetimeIndex to PeriodIndex.

Parameters:
freqstr, default None
Frequency associated with the PeriodIndex.

copybool, default True
Whether or not to return a copy.

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

Returns:
Series
Series with index converted to PeriodIndex.
98-2、参数

98-2-1、freq(可选,默认值为None)指定时间段的频率(如'D'表示日,'M'表示月),如果不指定,方法会根据Series的数据自动推断频率。

98-2-2、copy(可选,默认值为None)布尔值,如果为True,会返回副本;如果为False,会返回视图;如果没有特别需求,通常可以使用默认值。

98-3、功能

        用于将Series对象的时间戳数据转换为Period对象,Period对象对象代表特定的时间段(如日、月、年等),而不是单一的时间点。

98-4、返回值

        返回一个Period类型的Series,其频率由freq参数指定。

98-5、说明

        无

98-6、用法
98-6-1、数据准备
98-6-2、代码示例
# 98、pandas.Series.to_period方法
import pandas as pd
# 创建一个DatetimeIndex,这次我们为每个年份指定一个具体的日期(例如,每年的1月1日)
idx = pd.DatetimeIndex(['2023-01-01', '2024-01-01', '2025-01-01'])
# 创建一个Series,使用上述索引
s = pd.Series([1, 2, 3], index=idx)
# 现在我们可以安全地将Series转换为Period类型,这里我们将其转换为年度周期
s = s.to_period('Y')
print(s)
98-6-3、结果输出
# 98、pandas.Series.to_period方法
# 2023    1
# 2024    2
# 2025    3
# Freq: Y-DEC, dtype: int64
99、pandas.Series.to_timestamp方法
99-1、语法
# 99、pandas.Series.to_timestamp方法
pandas.Series.to_timestamp(freq=None, how='start', copy=None)
Cast to DatetimeIndex of Timestamps, at beginning of period.

Parameters:
freqstr, default frequency of PeriodIndex
Desired frequency.

how{‘s’, ‘e’, ‘start’, ‘end’}
Convention for converting period to timestamp; start of period vs. end.

copybool, default True
Whether or not to return a copy.

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

Returns:
Series with DatetimeIndex
99-2、参数

99-2-1、freq(可选,默认值为None)指定转换后的时间戳的频率,可以是'D'(日频率)、'H'(小时频率)、'T'(分钟频率)等,如果不指定(默认为None),则时间戳的频率与原周期相同。

99-2-2、how(可选,默认值为'start')指定周期的起始时间或结束时间,可以取以下两个值:

99-2-2-1、'start':周期的开始时间。

99-2-2-2、'end':周期的结束时间。

99-2-3、copy(可选,默认值为None)是否返回一个副本,设置为True时,返回一个新的Series对象,不修改原始数据;设置为False时,直接在原数据上进行操作;如果为None,则依据是否可以在原地操作来决定是否返回副本。

99-3、功能

        用于将PeriodIndex或Period对象的Series转换为DatetimeIndex对象的Series。

99-4、返回值

        返回一个Series对象,其中的索引为DatetimeIndex对象,包含了每个周期的时间戳(根据how参数的设置)。如果指定了freq参数,返回的Series将会应用该频率进行重采样。

99-5、说明

        无

99-6、用法
99-6-1、数据准备
99-6-2、代码示例
# 99、pandas.Series.to_timestamp方法
import pandas as pd
# 创建一个DatetimeIndex,这次我们为每个年份指定一个具体的日期(例如,每年的1月1日)
idx = pd.DatetimeIndex(['2023-01-01', '2024-01-01', '2025-01-01'])
# 创建一个Series,使用上述索引
s = pd.Series([1, 2, 3], index=idx)
# 将Series的索引转换为PeriodIndex
s_period = s.index.to_period('Y')
# 将PeriodIndex转换为时间戳,如何使用 'start' 参数
s_timestamp = s_period.to_timestamp(how='start')
# 使用新的时间戳索引创建Series
s = pd.Series(s.values, index=s_timestamp)
print(s)
99-6-3、结果输出
# 99、pandas.Series.to_timestamp方法
# 2023-01-01    1
# 2024-01-01    2
# 2025-01-01    3
# Freq: YS-JAN, dtype: int64
100、pandas.Series.to_list方法
100-1、语法
# 100、pandas.Series.to_list方法
pandas.Series.to_list()
Return a list of the values.

These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period)

Returns:
list
100-2、参数

        无

100-3、功能

        用于将Series对象转换为Python的列表(list)。

100-4、返回值

        返回一个Python列表,其中包含Series对象中的所有数据元素。

100-5、说明

        无

100-6、用法
100-6-1、数据准备
100-6-2、代码示例
# 100、pandas.Series.to_list方法
import pandas as pd
# 创建一个Series对象
data = pd.Series([10, 20, 30, 40, 50])
# 将Series转换为列表
data_list = data.to_list()
print(data_list)
100-6-3、结果输出
# 100、pandas.Series.to_list方法
# [10, 20, 30, 40, 50]

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
  • 15
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神奇夜光杯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值