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

目录

一、用法精讲

111、pandas.Series.item方法

111-1、语法

111-2、参数

111-3、功能

111-4、返回值

111-5、说明

111-6、用法

111-6-1、数据准备

111-6-2、代码示例

111-6-3、结果输出

112、pandas.Series.xs方法

112-1、语法

112-2、参数

112-3、功能

112-4、返回值

112-5、说明

112-6、用法

112-6-1、数据准备

112-6-2、代码示例

112-6-3、结果输出

113、pandas.Series.add方法

113-1、语法

113-2、参数

113-3、功能

113-4、返回值

113-5、说明

113-6、用法

113-6-1、数据准备

113-6-2、代码示例

113-6-3、结果输出

114、pandas.Series.sub方法

114-1、语法

114-2、参数

114-3、功能

114-4、返回值

114-5、说明

114-6、用法

114-6-1、数据准备

114-6-2、代码示例

114-6-3、结果输出

115、pandas.Series.mul方法

115-1、语法

115-2、参数

115-3、功能

115-4、返回值

115-5、说明

115-6、用法

115-6-1、数据准备

115-6-2、代码示例

115-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

111、pandas.Series.item方法
111-1、语法
# 111、pandas.Series.item方法
pandas.Series.item()
Return the first element of the underlying data as a Python scalar.

Returns:
scalar
The first element of Series or Index.

Raises:
ValueError
If the data is not length = 1.
111-2、参数

        无

111-3、功能

        用于从pandas.Series对象中获取单一的元素值,并返回该值。

111-4、返回值

        返回Series中唯一元素的值。

111-5、说明

        在使用item方法之前,可以考虑检查Series的长度,以确保安全调用。

111-6、用法
111-6-1、数据准备
111-6-2、代码示例
# 111、pandas.Series.item方法
import pandas as pd
# 创建一个只有一个元素的Series对象
s = pd.Series([42])
# 使用item方法获取这个元素
if len(s) == 1:
    value = s.item()
else:
    print("Series does not contain exactly one element.")
print(value)
111-6-3、结果输出
# 111、pandas.Series.item方法
# 42
112、pandas.Series.xs方法
112-1、语法
# 112、pandas.Series.xs方法
pandas.Series.xs(key, axis=0, level=None, drop_level=True)
Return cross-section from the Series/DataFrame.

This method takes a key argument to select data at a particular level of a MultiIndex.

Parameters:
key
label or tuple of label
Label contained in the index, or partially in a MultiIndex.

axis
{0 or ‘index’, 1 or ‘columns’}, default 0
Axis to retrieve cross-section on.

level
object, defaults to first n levels (n=1 or len(key))
In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position.

drop_level
bool, default True
If False, returns object with same levels as self.

Returns:
Series or DataFrame
Cross-section from the original Series or DataFrame corresponding to the selected index levels.
112-2、参数

112-2-1、key(必须)任意数据类型,通常为索引标签,表示要提取的索引标签值,如果Series有多层索引,则key可以是一个具体的层级标签(对于多层索引,需要指定level)。

112-2-2、axis(可选,默认值为0)一个整数或字符串,表示指定操作的轴。对于Series来说,axis总是 0,因为Series只有一个轴,表示索引轴;在多层索引的DataFrame中,这个参数允许指定不同的轴。

112-2-3、level(可选,默认值为None)一个整数或字符串,表示指定要在多层索引中提取的具体层级。如果Series没有多层索引,此参数被忽略。如果指定此参数,则key应为指定层级的标签值。例如,在多层索引的Series中,可以通过指定level来选择特定的层级。

112-2-4、drop_level(可选,默认值为True)布尔值,表示指定在提取值后是否从结果中删除所使用的层级。如果为True,提取的结果将不包含使用的索引层级;如果为False,结果将保留该层级的索引。

112-3、功能

        用于从一个pandas.Series对象中选择特定的数据,该方法可以通过给定的索引标签来切片Series,并返回与该标签对应的值。

112-4、返回值

        返回指定索引标签对应的单个值,或者如果key匹配多个值,则返回一个新的Series。

112-5、说明

112-5-1、如果指定的key不存在于索引中,会引发KeyError。

112-5-2、当使用level时,确保Series是多层索引的,否则指定level参数会导致错误。

112-5-3、drop_level的设置会影响结果的索引结构,True时会去掉提取的层级,False时保留。

112-6、用法
112-6-1、数据准备
112-6-2、代码示例
# 112、pandas.Series.xs方法
# 112-1、基本应用
import pandas as pd
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
# 获取索引为'b'的值
value = s.xs('b')
print(value, end='\n\n')

# 112-2、多层索引示例
import pandas as pd
# 创建多层索引的 Series
arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letters', 'numbers'))
s_multi = pd.Series([100, 200, 300, 400], index=index)
# 获取数字为1的所有值,保持原始层级
value = s_multi.xs(1, level='numbers', drop_level=False)
print(value, end='\n\n')
# 获取数字为1的所有值,删除层级
value = s_multi.xs(1, level='numbers', drop_level=True)
print(value)
112-6-3、结果输出
# 112、pandas.Series.xs方法
# 112-1、基本应用
# 20

# 112-2、多层索引示例
# 获取数字为1的所有值,保持原始层级
# letters  numbers
# A        1          100
# B        1          300
# dtype: int64

# 获取数字为1的所有值,删除层级
# letters
# A    100
# B    300
# dtype: int64
113、pandas.Series.add方法
113-1、语法
# 113、pandas.Series.add方法
pandas.Series.add(other, level=None, fill_value=None, axis=0)
Return Addition of series and other, element-wise (binary operator add).

Equivalent to series + other, but with support to substitute a fill_value for missing data in either one of the inputs.

Parameters:
other
Series or scalar value
level
int or name
Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_value
None or float value, default None (NaN)
Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.

axis
{0 or ‘index’}
Unused. Parameter needed for compatibility with DataFrame.

Returns:
Series
The result of the operation.
113-2、参数

113-2-1、other(必须)表示要与当前Series对象进行加法操作的对象。如果是Series或DataFrame,则将其与当前Series对象按元素逐一加法;如果是标量值,则该值会与Series中的每一个元素相加。

113-2-2、level(可选,默认值为None)一个整数或字符串,如果other是一个多层索引的Series或DataFrame,可以通过指定此参数来对齐相同的层级进行加法,level用于指明要对齐的层级标签。

113-2-3、fill_value(可选,默认值为None)标量值,当other中存在缺失值(NaN)时,用于填充缺失的值,即当other中某些索引标签在Series中不存在时,使用此值填补。

113-2-4、axis(可选,默认值为0)一个整数或字符串,表示指定沿哪个轴进行操作。对于Series,此参数通常被忽略,因为Series只有一个轴;对于DataFrame,则可以指定沿行或列进行操作。

113-3、功能

        用于执行两个Series对象之间的逐元素加法操作。

113-4、返回值

        返回一个新的Series对象,其中的每个元素是原Series和other对应位置元素的和。返回的Series的索引是Series与other的并集,如果other的索引中有当前Series中不存在的标签,这些标签对应的值会是填充值(如果设置了fill_value)或NaN(如果没有设置fill_value)。

113-5、说明

113-5-1、如果other的索引不完全匹配Series的索引,并且fill_value参数没有设置,缺失值会导致结果中的NaN。

113-5-2、使用fill_value可以处理缺失值,使加法操作更加鲁棒。

113-5-3、当涉及到多层索引时,确保level参数正确指定,以保证对齐的准确性。

113-6、用法
113-6-1、数据准备
113-6-2、代码示例
# 113、pandas.Series.add方法
# 113-1、基本用法
import pandas as pd
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index=['a', 'b', 'c'])
# 执行逐元素加法
result = s1.add(s2)
print(result, end='\n\n')

# 113-2、使用标量值
import pandas as pd
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index=['a', 'b', 'c'])
# 使用标量值进行加法
result = s1.add(10)
print(result, end='\n\n')

# 113-3、使用fill_value参数
import pandas as pd
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index=['a', 'b', 'c'])
s3 = pd.Series([7, 8], index=['a', 'd'])
result = s1.add(s3, fill_value=0)
print(result, end='\n\n')

# 113-4、使用多层索引
import pandas as pd
# 创建多层索引的Series
arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letters', 'numbers'))
s_multi1 = pd.Series([10, 20, 30, 40], index=index)
s_multi2 = pd.Series([1, 2, 3, 4], index=index)
# 执行逐元素加法
result_multi = s_multi1.add(s_multi2)
print(result_multi)
113-6-3、结果输出
# 113、pandas.Series.add方法
# 113-1、基本用法
# a    5
# b    7
# c    9
# dtype: int64

# 113-2、使用标量值
# a    11
# b    12
# c    13
# dtype: int64

# 113-3、使用fill_value参数
# a    8.0
# b    2.0
# c    3.0
# d    8.0
# dtype: float64

# 113-4、使用多层索引
# letters  numbers
# A        1          11
#          2          22
# B        1          33
#          2          44
# dtype: int64
114、pandas.Series.sub方法
114-1、语法
# 114、pandas.Series.sub方法
pandas.Series.sub(other, level=None, fill_value=None, axis=0)
Return Subtraction of series and other, element-wise (binary operator sub).

Equivalent to series - other, but with support to substitute a fill_value for missing data in either one of the inputs.

Parameters:
other
Series or scalar value
level
int or name
Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_value
None or float value, default None (NaN)
Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.

axis
{0 or ‘index’}
Unused. Parameter needed for compatibility with DataFrame.

Returns:
Series
The result of the operation.
114-2、参数

114-2-1、other(必须)被减数,可以是与当前Series对象相同长度的Series、DataFrame或一个标量值,如果是DataFrame,则会对每列执行相应的减法操作。

114-2-2、level(可选,默认值为None)一个整数或字符串,如果当前Series或other有多层索引(MultiIndex),level参数用于指定在哪一层索引上对齐,这样可以在指定层级上进行逐元素减法运算,而不是在所有层级上。

114-2-3、fill_value(可选,默认值为None)标量值,当other的某些索引值在当前Series中不存在时,使用fill_value来填补这些缺失值,这样,fill_value代替了缺失的数据参与计算。

114-2-4、axis(可选,默认值为0)这个参数主要在DataFrame上有效,用于指定操作的轴;在Series上,通常没有必要设置这个参数,因为Series只有一个轴(轴0)。

114-3、功能

        用于对两个Series对象进行逐元素的减法操作。

114-4、返回值

        返回一个新的Series对象,其中的每个元素是原Series和other对应位置元素的差。返回的Series的索引是Series与other的并集,如果other的索引中有当前Series中不存在的标签,这些标签对应的值会是填充值(如果设置了fill_value)或NaN(如果没有设置fill_value)。

114-5、说明

        无

114-6、用法
114-6-1、数据准备
114-6-2、代码示例
# 114、pandas.Series.sub方法
# 114-1、基本用法
import pandas as pd
s1 = pd.Series([5, 6, 7], index=['a', 'b', 'c'])
s2 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
result = s1.sub(s2)
print(result, end='\n\n')

# 114-2、使用level参数
import pandas as pd
arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letters', 'numbers'))
s1 = pd.Series([10, 20, 30, 40], index=index)
s2 = pd.Series([1, 2, 3, 4], index=index)
result = s1.sub(s2, level='letters')
print(result, end='\n\n')

# 114-3、使用fill_value参数
import pandas as pd
s1 = pd.Series([5, 6], index=['a', 'b'])
s2 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
result = s1.sub(s2, fill_value=0)
print(result, end='\n\n')

# 114-4、使用axis参数(主要适用于DataFrame)
import pandas as pd
df1 = pd.DataFrame({'A': [10, 20], 'B': [30, 40]})
df2 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
result = df1.sub(df2, axis=0)
print(result)
114-6-3、结果输出
# 114、pandas.Series.sub方法
# 114-1、基本用法
# a    4
# b    4
# c    4
# dtype: int64

# 114-2、使用level参数
# letters  numbers
# A        1           9
#          2          18
# B        1          27
#          2          36
# dtype: int64

# 114-3、使用fill_value参数
# a    4.0
# b    4.0
# c   -3.0
# dtype: float64

# 114-4、使用axis参数(主要适用于DataFrame)
#     A   B
# 0   9  27
# 1  18  36
115、pandas.Series.mul方法
115-1、语法
# 115、pandas.Series.mul方法
pandas.Series.mul(other, level=None, fill_value=None, axis=0)
Return Multiplication of series and other, element-wise (binary operator mul).

Equivalent to series * other, but with support to substitute a fill_value for missing data in either one of the inputs.

Parameters:
other
Series or scalar value
level
int or name
Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_value
None or float value, default None (NaN)
Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.

axis
{0 or ‘index’}
Unused. Parameter needed for compatibility with DataFrame.

Returns:
Series
The result of the operation.
115-2、参数

115-2-1、other(必须)乘数,可以是与当前Series对象长度相同的Series、DataFrame或一个标量值。如果是DataFrame,会对每列进行逐元素的乘法操作。

115-2-2、level(可选,默认值为None)如果当前Series或other有多层索引(MultiIndex),level参数用于指定在哪一层索引上对齐,这样可以在指定层级上进行逐元素乘法运算,而不是在所有层级上。

115-2-3、fill_value(可选,默认值为None)当other的某些索引值在当前Series中不存在时,使用fill_value来填补这些缺失值,这样,fill_value代替了缺失的数据参与计算。

115-2-4、axis(可选,默认值为0)主要在DataFrame上有效,用于指定操作的轴;在Series上,通常没有必要设置这个参数,因为Series只有一个轴(轴0)。

115-3、功能

        用于执行元素级的乘法操作。具体来说,它会将Series中的每个元素与另一个序列(Series或兼容的数组类型,如NumPy数组)中的对应元素相乘。如果不存在对应元素(比如两个Series的索引不完全匹配),则可以通过fill_value参数来指定一个填充值,以便进行乘法操作。

115-4、返回值

        返回一个新的Series,其中包含原始Series和other参数指定的序列(或数组)之间元素级乘法的结果。如果两个输入序列的索引不完全匹配,并且指定了fill_value,则结果Series的索引将是两个输入序列索引的并集,缺失值将用fill_value替换以进行乘法操作。

115-5、说明

        无

115-6、用法
115-6-1、数据准备
115-6-2、代码示例
# 115、pandas.Series.mul方法
# 115-1、基本用法
import pandas as pd
s1 = pd.Series([2, 3, 4], index=['a', 'b', 'c'])
s2 = pd.Series([5, 6, 7], index=['a', 'b', 'c'])
result = s1.mul(s2)
print(result, end='\n\n')

# 115-2、使用level参数
import pandas as pd
arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letters', 'numbers'))
s1 = pd.Series([10, 20, 30, 40], index=index)
s2 = pd.Series([2, 3, 4, 5], index=index)
result = s1.mul(s2, level='letters')
print(result, end='\n\n')

# 115-3、使用fill_value参数
import pandas as pd
s1 = pd.Series([1, 2], index=['a', 'b'])
s2 = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
result = s1.mul(s2, fill_value=1)
print(result, end='\n\n')

# 115-4、使用axis参数(主要适用于DataFrame)
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [10, 20], 'B': [30, 40]})
result = df1.mul(df2, axis=0)
print(result)
115-6-3、结果输出
# 115、pandas.Series.mul方法
# 115-1、基本用法
# a    10
# b    18
# c    28
# dtype: int64

# 115-2、使用level参数
# letters  numbers
# A        1           20
#          2           60
# B        1          120
#          2          200
# dtype: int64

# 115-3、使用fill_value参数
# a    10.0
# b    40.0
# c    30.0
# dtype: float64

# 115-4、使用axis参数(主要适用于DataFrame)
#     A    B
# 0  10   90
# 1  40  160

二、推荐阅读

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神奇夜光杯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值