目录
907、pandas.Index.searchsorted方法
908、pandas.Index.sort_values方法
一、用法精讲
906、pandas.Index.argsort方法
906-1、语法
# 906、pandas.Index.argsort方法
pandas.Index.argsort(*args, **kwargs)
Return the integer indices that would sort the index.
Parameters:
*args
Passed to numpy.ndarray.argsort.
**kwargs
Passed to numpy.ndarray.argsort.
Returns:
np.ndarray[np.intp]
Integer indices that would sort the index if used as an indexer.
906-2、参数
906-2-1、*args(可选):其他位置参数,为后续扩展功能做预留。
906-2-2、**kwargs(可选):其他关键字参数,常见的关键字参数包括:
- axis:定义排序的轴,默认为-1(最后一个轴)。
- kind:指定排序算法,可以是'quicksort'、'mergesort'、'heapsort'等。
- order:用于对结构化数组进行排序的字段名。
906-3、功能
用于对Index对象进行排序并返回排序结果的整数位置。
906-4、返回值
返回值是一个整数数组,数组中的每个元素对应于原始索引在排序后索引中的位置。例如,如果原始索引的排列为[3, 1, 2],则argsort的返回值将是[1, 2, 0],表示1在排序后的第一位,2在第二位,而3在第三位。
906-5、说明
无
906-6、用法
906-6-1、数据准备
无
906-6-2、代码示例
# 906、pandas.Index.argsort方法
import pandas as pd
# 创建一个Index对象
index = pd.Index([3, 1, 2])
# 使用argsort方法
sorted_indices = index.argsort()
# 输出结果
print(sorted_indices)
906-6-3、结果输出
# 906、pandas.Index.argsort方法
# [1 2 0]
907、pandas.Index.searchsorted方法
907-1、语法
# 907、pandas.Index.searchsorted方法
pandas.Index.searchsorted(value, side='left', sorter=None)
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted Index self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved.
Note
The Index must be monotonically sorted, otherwise wrong locations will likely be returned. Pandas does not check this for you.
Parameters:
value
array-like or scalar
Values to insert into self.
side
{‘left’, ‘right’}, optional
If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self).
sorter
1-D array-like, optional
Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort.
Returns:
int or array of int
A scalar or array of insertion points with the same shape as value.
907-2、参数
907-2-1、value(必需):标量或数组,表示要查找的值或值的数组,在索引中查找这个值的位置。
907-2-2、side(可选,默认值为'left'):{'left', 'right'},决定了插入位置的选择:
- 'left':返回插入位置的下标,该位置的值等于或大于给定值。
- 'right':返回插入位置的下标,该位置的值严格大于给定值。
907-2-3、sorter(可选,默认值为None):array-like,用于排序的索引,如果提供了这个参数,将根据此排序进行查找,该参数应该是一个整数数组,表示索引顺序的排列。
907-3、功能
用于查找一个值在已排序索引中的插入位置,可以帮助用户快速确定在不改变索引顺序的情况下,如何添加或插入新值。
907-4、返回值
返回一个整数(或整数数组,如果value是数组的话),表示插入位置的下标,可以是一个或多个整数,具体取决于输入值的类型。
907-5、说明
无
907-6、用法
907-6-1、数据准备
无
907-6-2、代码示例
# 907、pandas.Index.searchsorted方法
import pandas as pd
index = pd.Index([1, 3, 5, 7, 9])
position = index.searchsorted(4)
print(position)
907-6-3、结果输出
# 907、pandas.Index.searchsorted方法
# 2
908、pandas.Index.sort_values方法
908-1、语法
# 908、pandas.Index.sort_values方法
pandas.Index.sort_values(*, return_indexer=False, ascending=True, na_position='last', key=None)
Return a sorted copy of the index.
Return a sorted copy of the index, and optionally return the indices that sorted the index itself.
Parameters:
return_indexer
bool, default False
Should the indices that would sort the index be returned.
ascending
bool, default True
Should the index values be sorted in an ascending order.
na_position
{‘first’ or ‘last’}, default ‘last’
Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.
key
callable, optional
If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape.
Returns:
sorted_index
pandas.Index
Sorted copy of the index.
indexer
numpy.ndarray, optional
The indices that the index itself was sorted by.
908-2、参数
908-2-1、return_indexer(可选,默认值为False):布尔值,如果设为True,将返回排序后的索引和一个数组,该数组表示原始索引的排序顺序。
908-2-2、ascending(可选,默认值为True):布尔值,决定排序的顺序,如果设置为True,则进行升序排序;如果设置为False,则进行降序排序。
908-2-3、na_position(可选,默认值为'last'):{'first', 'last'},在排序过程中指定NA(缺失值)的位置,'first'会将NA值放在前面,而'last'则将其放在最后。
908-2-4、key(可选,默认值为None):function,用于对索引值进行处理,它可以用来转换索引中的每个元素,之后再进行排序。例如,可以传入str.lower以对字符串进行不区分大小写的排序。
908-3、功能
用于对索引进行排序,该方法返回一个新的索引对象,其中的值已经经过排序。
908-4、返回值
返回一个新的索引对象,包含已排序的值,若return_indexer=True,还会返回一个索引器,指示原始索引的排序顺序。
908-5、说明
无
908-6、用法
908-6-1、数据准备
无
908-6-2、代码示例
# 908、pandas.Index.sort_values方法
import pandas as pd
# 创建一个索引
index = pd.Index([5, 2, 9, None, 1])
# 对索引进行排序
sorted_index = index.sort_values()
print(sorted_index)
# 进行降序排序并返回索引器
sorted_index, indexer = index.sort_values(return_indexer=True, ascending=False)
print(sorted_index)
print(indexer)
908-6-3、结果输出
# 908、pandas.Index.sort_values方法
# Index([1.0, 2.0, 5.0, 9.0, nan], dtype='float64')
# Index([9.0, 5.0, 2.0, 1.0, nan], dtype='float64')
# [2 0 1 4 3]
909、pandas.Index.shift方法
909-1、语法
# 909、pandas.Index.shift方法
pandas.Index.shift(periods=1, freq=None)
Shift index by desired number of time frequency increments.
This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times.
Parameters:
periods
int, default 1
Number of periods (or increments) to shift by, can be positive or negative.
freq
pandas.DateOffset, pandas.Timedelta or str, optional
Frequency increment to shift by. If None, the index is shifted by its own freq attribute. Offset aliases are valid strings, e.g., ‘D’, ‘W’, ‘M’ etc.
Returns:
pandas.Index
Shifted index.
909-2、参数
909-2-1、periods(可选,默认值为1):一个整数值,表示要移动的时间步数,正值表示向前移动,负值表示向后移动。例如,periods=1将会把索引值向前移动一个单位。
909-2-2、freq(可选,默认值为None):str, DateOffset or None,用于指定频率,仅在索引是时间戳类型时有效,你可以使用字符串(如'D'表示日,'M'表示月等),或使用pd.DateOffset等对象来定义偏移量,如果设置为None,则不考虑频率,仅按位置移动。
909-3、功能
通过指定的步数或频率来移动索引值,在时间序列分析中非常有用,例如为了计算滞后值、变化率等。
909-4、返回值
返回一个新的索引对象,其值是原始索引的偏移版本,原有的值在偏移后会被填充为NaN或相应的缺失值,可以帮助用户在数据分析时更好地处理时间序列数据。
909-5、说明
无
909-6、用法
909-6-1、数据准备
无
909-6-2、代码示例
# 909、pandas.Index.shift方法
import pandas as pd
# 创建一个时间序列
date_range = pd.date_range(start='2024-11-05', periods=5, freq='D')
index = pd.Index(date_range)
# 使用shift方法
shifted_index = index.shift(periods=1)
print("原始索引:")
print(index)
print("偏移后的索引:")
print(shifted_index)
909-6-3、结果输出
# 909、pandas.Index.shift方法
# 原始索引:
# DatetimeIndex(['2024-11-05', '2024-11-06', '2024-11-07', '2024-11-08',
# '2024-11-09'],
# dtype='datetime64[ns]', freq='D')
# 偏移后的索引:
# DatetimeIndex(['2024-11-06', '2024-11-07', '2024-11-08', '2024-11-09',
# '2024-11-10'],
# dtype='datetime64[ns]', freq='D')
910、pandas.Index.append方法
910-1、语法
# 910、pandas.Index.append方法
pandas.Index.append(other)
Append a collection of Index options together.
Parameters:
other
Index or list/tuple of indices
Returns:
Index
910-2、参数
910-2-1、other(必需):可以是另一个Index对象,或者是一个包含多个Index对象的列表或元组。
910-3、功能
将多个索引对象合并成一个新的索引对象,当你传入多个索引时,这些索引会被按顺序拼接在一起,形成一个新的索引。
910-4、返回值
返回一个新的Index对象,包含所有传入的索引元素。
910-5、说明
无
910-6、用法
910-6-1、数据准备
无
910-6-2、代码示例
# 910、pandas.Index.append方法
import pandas as pd
# 创建两个索引
idx1 = pd.Index([1, 2, 3])
idx2 = pd.Index([4, 5, 6])
# 使用append方法合并这两个索引
new_idx = idx1.append(idx2)
print(new_idx)
idx3 = pd.Index([7, 8, 9])
new_idx = idx1.append([idx2, idx3])
print(new_idx)
910-6-3、结果输出
# 910、pandas.Index.append方法
# Index([1, 2, 3, 4, 5, 6], dtype='int64')
# Index([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')