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

目录

一、用法精讲

436、pandas.DataFrame.tail方法

436-1、语法

436-2、参数

436-3、功能

436-4、返回值

436-5、说明

436-6、用法

436-6-1、数据准备

436-6-2、代码示例

436-6-3、结果输出

437、pandas.DataFrame.xs方法

437-1、语法

437-2、参数

437-3、功能

437-4、返回值

437-5、说明

437-6、用法

437-6-1、数据准备

437-6-2、代码示例

437-6-3、结果输出

438、pandas.DataFrame.get方法

438-1、语法

438-2、参数

438-3、功能

438-4、返回值

438-5、说明

438-6、用法

438-6-1、数据准备

438-6-2、代码示例

438-6-3、结果输出

439、pandas.DataFrame.isin方法

439-1、语法

439-2、参数

439-3、功能

439-4、返回值

439-5、说明

439-6、用法

439-6-1、数据准备

439-6-2、代码示例

439-6-3、结果输出

440、pandas.DataFrame.where方法

440-1、语法

440-2、参数

440-3、功能

440-4、返回值

440-5、说明

440-6、用法

440-6-1、数据准备

440-6-2、代码示例

440-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

436、pandas.DataFrame.tail方法
436-1、语法
# 436、pandas.DataFrame.tail方法
pandas.DataFrame.tail(n=5)
Return the last n rows.

This function returns last n rows from the object based on position. It is useful for quickly verifying data, for example, after sorting or appending rows.

For negative values of n, this function returns all rows except the first |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:
type of caller
The last n rows of the caller object.
436-2、参数

436-2-1、n(可选,默认值为5)用于指定要返回的最后几行的数量,n的值必须为非负整数,如果n大于DataFrame中的总行数,则返回整个DataFrame。

436-3、功能

        提供快速访问DataFrame的最后几行数据,这在数据分析和数据处理时非常有用,尤其是在你需要检查数据的结尾部分,看看是否有缺失值或者获取最后几条记录的情况下。

436-4、返回值

        返回一个新的DataFrame,包含原DataFrame的最后n行,如果n的值小于1,则返回一个空的DataFrame。

436-5、说明

        无

436-6、用法
436-6-1、数据准备
436-6-2、代码示例
# 436、pandas.DataFrame.tail方法
import pandas as pd
# 创建示例DataFrame
data = {
    'A': [1, 2, 3, 4, 5],
    'B': ['a', 'b', 'c', 'd', 'e'],
    'C': [True, False, True, False, True]
}
df = pd.DataFrame(data)
# 使用tail()方法
last_rows = df.tail(3)
print(last_rows)
436-6-3、结果输出
# 436、pandas.DataFrame.tail方法
#    A  B      C
# 2  3  c   True
# 3  4  d  False
# 4  5  e   True
437、pandas.DataFrame.xs方法
437-1、语法
# 437、pandas.DataFrame.xs方法
pandas.DataFrame.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.
437-2、参数

437-2-1、key(必须)要选择的行或列的标签,具体取决于axis参数的设置。

437-2-2、axis(可选,默认值为0)指定要选择的轴,可以是0(行)或1(列)。

437-2-3、level(可选,默认值为None)如果DataFrame有多层索引,level参数用于指定要选择的索引级别,可以是层的名称或者层的编号。

437-2-4、drop_level(可选,默认值为True)布尔值,如果设置为True(默认值),选择后将删除被选层的标签;如果设置为False,则会保留该层的标签。

437-3、功能

        根据指定的key从DataFrame中提取数据,它可以用于选择多层索引(MultiIndex)中的特定级别的数据,方便我们对多维数据进行访问。

437-4、返回值

        返回一个新的DataFrame或者Series,具体取决于选择的结果。如果选择了唯一一行,则返回的是一个Series;如果选择了多行,则返回一个DataFrame。

437-5、说明

        无

437-6、用法
437-6-1、数据准备
437-6-2、代码示例
# 437、pandas.DataFrame.xs方法
import pandas as pd
# 创建一个示例DataFrame
data = {
    'A': [1, 2, 3, 4],
    'B': [5, 6, 7, 8]
}
df = pd.DataFrame(data, index=pd.MultiIndex.from_tuples([('foo', 1), ('foo', 2), ('bar', 1), ('bar', 2)], names=['first', 'second']))
# 使用xs()方法选择数据
result = df.xs('foo')  # 选择'foo'这一层的所有行
print(result, end='\n\n')
# 选择特定的层级
result_level = df.xs(1, level='second')  # 选择'second'级别为1的所有行
print(result_level)
437-6-3、结果输出
# 437、pandas.DataFrame.xs方法
#         A  B
# second      
# 1       1  5
# 2       2  6
# 
#        A  B
# first      
# foo    1  5
# bar    3  7
438、pandas.DataFrame.get方法
438-1、语法
# 438、pandas.DataFrame.get方法
pandas.DataFrame.get(key, default=None)
Get item from object for given key (ex: DataFrame column).

Returns default value if not found.

Parameters:
key
object
Returns:
same type as items contained in object.
438-2、参数

438-2-1、key(必须)要获取的列的标签,可以是单个列名字符串,或者是一个包含多个列名的列表。

438-2-2、default(可选,默认值为None)当指定的列名不存在时返回的默认值。

438-3、功能

        根据指定的key从DataFrame中获取列,如果该列不存在,则返回指定的默认值,这使得代码在访问DataFrame时更加健壮,避免因访问不存在的列而导致的错误。

438-4、返回值

        返回与指定的key相对应的列数据,如果给定的key是单个列名,将返回一个Series;如果给定的key是列名的列表,则返回一个DataFrame;如果所请求的列不存在,则返回default参数指定的值(默认为None)。

438-5、说明

        无

438-6、用法
438-6-1、数据准备
438-6-2、代码示例
# 438、pandas.DataFrame.get方法
import pandas as pd
# 创建一个示例DataFrame
data = {
    'A': [1, 2, 3],
    'B': [4, 5, 6]
}
df = pd.DataFrame(data)
# 使用get()方法获取存在的列
result_a = df.get('A')
print(result_a, end='\n\n')
# 使用get()方法获取不存在的列,返回默认值
result_c = df.get('C', default='Column not found')
print(result_c, end='\n\n')
# 使用get()方法获取多个列
result_multiple = df.get(['A', 'B'])
print(result_multiple, end='\n\n')
# 使用get()方法获取不存在的多个列,并返回默认值
result_multiple_default = df.get(['A', 'C'], default='Column not found')
print(result_multiple_default)
438-6-3、结果输出
# 438、pandas.DataFrame.get方法
# 0    1
# 1    2
# 2    3
# Name: A, dtype: int64
# 
# Column not found
# 
#    A  B
# 0  1  4
# 1  2  5
# 2  3  6
# 
# Column not found
439、pandas.DataFrame.isin方法
439-1、语法
# 439、pandas.DataFrame.isin方法
pandas.DataFrame.isin(values)
Whether each element in the DataFrame is contained in values.

Parameters:
values
iterable, Series, DataFrame or dict
The result will only be true at a location if all the labels match. If values is a Series, that’s the index. If values is a dict, the keys must be the column names, which must match. If values is a DataFrame, then both the index and column labels must match.

Returns:
DataFrame
DataFrame of booleans showing whether each element in the DataFrame is contained in values.
439-2、参数

439-2-1、values(必须)要检查的值,可以是以下几种类型:

  • 单个标量值(如数字或字符串)
  • 列表(可以是单层列表或嵌套列表)
  • NumPy数组
  • Series
  • DataFrame
439-3、功能

        检测DataFrame中的元素是否包含在指定的值集合中,它返回一个与原DataFrame形状相同的布尔DataFrame,其中每个元素的值表示该元素是否在给定的值中。

439-4、返回值

        返回一个布尔型DataFrame,形状与原DataFrame相同,布尔值True表示原DataFrame中的对应元素在values中找到,而False则表示未找到。

439-5、说明

        无

439-6、用法
439-6-1、数据准备
439-6-2、代码示例
# 439、pandas.DataFrame.isin方法
import pandas as pd
# 创建一个示例DataFrame
data = {
    'A': [1, 2, 3, 4],
    'B': [5, 6, 7, 8],
    'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data)
# 使用isin()方法检查元素是否在指定的值中
result = df.isin([1, 2, 5, 10])
print(result)
439-6-3、结果输出
# 439、pandas.DataFrame.isin方法
#        A      B      C
# 0   True   True  False
# 1   True  False   True
# 2  False  False  False
# 3  False  False  False
440、pandas.DataFrame.where方法
440-1、语法
# 440、pandas.DataFrame.where方法
pandas.DataFrame.where(cond, other=nan, *, inplace=False, axis=None, level=None)
Replace values where the condition is False.

Parameters:
cond
bool Series/DataFrame, array-like, or callable
Where cond is True, keep the original value. Where False, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).

other
scalar, Series/DataFrame, or callable
Entries where cond is False are replaced with corresponding value from other. If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it). If not specified, entries will be filled with the corresponding NULL value (np.nan for numpy dtypes, pd.NA for extension dtypes).

inplace
bool, default False
Whether to perform the operation in place on the data.

axis
int, default None
Alignment axis if needed. For Series this parameter is unused and defaults to 0.

level
int, default None
Alignment level if needed.

Returns:
Same type as caller or None if
inplace=True.
440-2、参数

440-2-1、cond(必须)布尔型DataFrame或ndarray指定要保留的元素位置的布尔条件,True表示保留原值,False表示替换为other中的值。

440-2-2、other(可选,默认值为nan)标量、DataFrame、ndarray或Series替换掉cond中为False的位置的值。

440-2-3、inplace(可选,默认值为False)布尔值,如果设置为True,则在原地修改数据,不返回新的DataFrame;如果为False,返回一个新的DataFrame。

440-2-4、axis(可选,默认值为None){0或‘index’, 1或‘columns’},在应用函数时选择的轴,如果cond是DataFrame,则这个参数会被忽略。

440-2-5、level(可选,默认值为None)整数或级别名称,对于多级索引(MultiIndex),可以指定在哪个级别进行操作。

440-3、功能

        返回一个与原DataFrame形状相同的对象,对于那些在条件cond中满足的元素,保留原值,而对于不满足条件的元素,替换为other参数指定的值(默认是NaN)。

440-4、返回值

        如果inplace=False(默认),则返回一个新的DataFrame,其中根据条件进行了相应的替换;如果inplace=True,则返回值为None,原DataFrame会被直接修改。

440-5、说明

        无

440-6、用法
440-6-1、数据准备
440-6-2、代码示例
# 440、pandas.DataFrame.where方法
import pandas as pd
import numpy as np
# 创建示例DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3, 4],
    'B': [10, 20, 30, 40]
})
# 保留大于2的值,其他的替换为0
df_where = df.where(df > 2, other=0)
print(df_where)
440-6-3、结果输出
# 440、pandas.DataFrame.where方法
#    A   B
# 0  0  10
# 1  0  20
# 2  3  30
# 3  4  40

二、推荐阅读

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神奇夜光杯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值