Pandas-2-2-中文文档-二十七-
Pandas 2.2 中文文档(二十七)
pandas.Index
class pandas.Index(data=None, dtype=None, copy=False, name=None, tupleize_cols=True)
用于索引和对齐的不可变序列。
存储所有 pandas 对象轴标签的基本对象。
从版本 2.0.0 开始更改:索引可以保存所有 numpy 数值 dtypes(除了 float16)。以前只接受 int64/uint64/float64 dtypes。
参数:
data类似数组(1 维)
dtypestr、numpy.dtype 或 ExtensionDtype,可选
输出索引的数据类型���如果未指定,将从数据中推断。有关更多用法,请参阅用户指南。
copybool,默认值 False
复制输入数据。
name对象
要存储在索引中的名称。
tupleize_colsbool(默认值:True)
当为 True 时,尝试创建 MultiIndex(如果可能)。
另请参阅
RangeIndex
实现单调整数范围的索引。
CategoricalIndex
索引Categorical
s。
MultiIndex
多级或分层索引。
IntervalIndex
一个Interval
s 的索引。
DatetimeIndex
datetime64 数据的索引。
TimedeltaIndex
timedelta64 数据的索引。
PeriodIndex
期间数据的索引。
注意
索引实例只能包含可哈希对象。索引实例不能保存 numpy float16 dtype。
示例
>>> pd.Index([1, 2, 3])
Index([1, 2, 3], dtype='int64')
>>> pd.Index(list('abc'))
Index(['a', 'b', 'c'], dtype='object')
>>> pd.Index([1, 2, 3], dtype="uint8")
Index([1, 2, 3], dtype='uint8')
属性
T |
返回转置,根据定义为自身。 |
---|---|
array |
支持此 Series 或 Index 的数据的 ExtensionArray。 |
dtype |
返回基础数据的 dtype 对象。 |
empty |
|
has_duplicates |
检查索引是否具有重复值。 |
hasnans |
如果存在任何 NaN,则返回 True。 |
inferred_type |
返回从值推断的类型的字符串。 |
is_monotonic_decreasing |
如果值相等或递减,则返回布尔值。 |
is_monotonic_increasing |
返回一个布尔值,如果值相等或递增则为真。 |
is_unique |
返回索引是否具有唯一值。 |
name |
返回索引或多重索引的名称。 |
names |
|
nbytes |
返回底层数据中的字节数。 |
ndim |
底层数据的维数,定义为 1。 |
nlevels |
等级数。 |
shape |
返回底层数据的形状的元组。 |
size |
返回底层数据中的元素数。 |
values |
返回表示索引中数据的数组。 |
方法
all (*args, **kwargs) |
返回所有元素是否为真。 |
---|---|
any (*args, **kwargs) |
返回是否有任何元素为真。 |
append (other) |
将一组索引选项连接在一起。 |
argmax ([axis, skipna]) |
返回系列中最大值的整数位置。 |
argmin ([axis, skipna]) |
返回系列中最小值的整数位置。 |
argsort (*args, **kwargs) |
返回将索引排序的整数索引。 |
asof (label) |
返回索引中的标签,如果不存在,则返回前一个标签。 |
asof_locs (where, mask) |
返回索引中标签的位置(索引)。 |
astype (dtype[, copy]) |
创建一个将值转换为指定数据类型的索引。 |
copy ([name, deep]) |
复制此对象。 |
delete (loc) |
创建一个删除指定位置的新索引。 |
diff ([periods]) |
计算索引对象中连续值之间的差异。 |
difference (other[, sort]) |
返回一个新的索引,其中包含不在其他索引中的元素。 |
drop (labels[, errors]) |
使用传递的标签列表创建新的索引。 |
drop_duplicates (*[, keep]) |
返回删除重复值后的索引。 |
droplevel ([level]) |
返回删除请求级别的索引。 |
dropna ([how]) |
返回没有 NA/NaN 值的索引。 |
duplicated ([keep]) |
指示重复的索引值。 |
equals (other) |
确定两个索引对象是否相等。 |
factorize ([sort, use_na_sentinel]) |
将对象编码为枚举类型或分类变量。 |
fillna ([value, downcast]) |
使用指定的值填充 NA/NaN 值。 |
format ([name, formatter, na_rep]) |
渲染索引的字符串表示。 |
get_indexer (target[, method, limit, tolerance]) |
给定当前索引,计算新索引的索引器和掩码。 |
get_indexer_for (target) |
即使不唯一,也保证返回一个索引器。 |
get_indexer_non_unique (target) |
给定当前索引,计算新索引的索引器和掩码。 |
get_level_values (level) |
返回请求级别的值索引。 |
get_loc (key) |
获取请求标签的整数位置、切片或布尔遮罩。 |
get_slice_bound (label, side) |
计算与给定标签对应的切片边界。 |
groupby (values) |
根据给定的值数组对索引标签进行分组。 |
holds_integer () |
(已弃用)类型是否为整数类型。 |
identical (other) |
类似于 equals,但也检查对象属性和类型是否相等。 |
infer_objects ([copy]) |
如果有对象类型,���尝试推断非对象类型。 |
insert (loc, item) |
在指定位置插入新项目以创建新索引。 |
intersection (other[, sort]) |
形成两个索引对象的交集。 |
is_ (other) |
更灵活、更快速的检查,类似于 is ,但通过视图操作。 |
is_boolean () |
(已弃用) 检查索引是否仅由布尔值组成。 |
is_categorical () |
(已弃用) 检查索引是否包含分类数据。 |
is_floating () |
(已弃用) 检查索引是否为浮点类型。 |
is_integer () |
(已弃用) 检查索引是否仅由整数组成。 |
is_interval () |
(已弃用) 检查索引是否包含区间对象。 |
is_numeric () |
(已弃用) 检查索引是否仅由数值数据组成。 |
is_object () |
(已弃用) 检查索引是否为对象类型。 |
isin (values[, level]) |
返回一个布尔数组,其中索引值在给定值中。 |
isna () |
检测缺失值。 |
isnull () |
检测缺失值。 |
item () |
将底层数据的第一个元素作为 Python 标量返回。 |
join (other, *[, how, level, ...]) |
计算 join_index 和 indexers,以使数据结构符合新索引。 |
map (mapper[, na_action]) |
使用输入映射或函数映射值。 |
max ([axis, skipna]) |
返回索引的最大值。 |
memory_usage ([deep]) |
值的内存使用情况。 |
min ([axis, skipna]) |
返回索引的最小值。 |
notna () |
检测存在的(非缺失)值。 |
notnull () |
检测存在的(非缺失的)值。 |
nunique ([dropna]) |
返回对象中唯一元素的数量。 |
putmask (mask, value) |
返回使用掩码设置的值的新索引。 |
ravel ([order]) |
返回自身的视图。 |
reindex (target[, method, level, limit, ...]) |
使用目标值创建索引。 |
rename (name, *[, inplace]) |
更改索引或多重索引的名称。 |
repeat (repeats[, axis]) |
重复索引的元素。 |
round ([decimals]) |
将索引中的每个值四舍五入到给定的小数位数。 |
searchsorted (value[, side, sorter]) |
查找应插入元素以保持顺序的索引。 |
set_names (names, *[, level, inplace]) |
设置索引或多重索引的名称。 |
shift ([periods, freq]) |
按所需的时间频率增量移动索引。 |
slice_indexer ([start, end, step]) |
计算输入标签和步长的切片索引器。 |
slice_locs ([start, end, step]) |
计算输入标签的切片位置。 |
sort (*args, **kwargs) |
使用 sort_values 代替。 |
sort_values (*[, return_indexer, ascending, ...]) |
返回索引的排序副本。 |
sortlevel ([level, ascending, ...]) |
用于与索引 API 的内部兼容性。 |
symmetric_difference (other[, result_name, sort]) |
计算两个索引对象的对称差。 |
take (indices[, axis, allow_fill, fill_value]) |
返回由索引选定的值的新索引。 |
to_flat_index () |
身份方法。 |
to_frame ([index, name]) |
创建一个包含索引的列的 DataFrame。 |
to_list () |
返回值的列表。 |
to_numpy ([dtype, copy, na_value]) |
表示此 Series 或 Index 中值的 NumPy ndarray。 |
to_series ([index, name]) |
创建一个索引和值都等于索引键的 Series。 |
tolist () |
返回值的列表。 |
transpose (*args, **kwargs) |
返回转置,其定义为自身。 |
union (other[, sort]) |
形成两个索引对象的并集。 |
unique ([level]) |
返回索引中的唯一值。 |
value_counts ([normalize, sort, ascending, ...]) |
返回包含唯一值计数的 Series。 |
view ([cls]) |
|
where (cond[, other]) |
替换条件为 False 的值。 |
pandas.Index.values
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.values.html
property Index.values
返回表示索引中数据的数组。
警告
我们建议根据您是否需要底层数据的引用或 NumPy 数组来使用 Index.array
或 Index.to_numpy()
。
返回:
数组:numpy.ndarray 或 ExtensionArray
另请参见
Index.array
对底层数据的引用。
Index.to_numpy
表示底层数据的 NumPy 数组。
示例
对于pandas.Index
:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.values
array([1, 2, 3])
对于pandas.IntervalIndex
:
>>> idx = pd.interval_range(start=0, end=5)
>>> idx.values
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]
pandas.Index.is_monotonic_increasing
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_monotonic_increasing.html
property Index.is_monotonic_increasing
如果数值相等或递增,则返回布尔值。
返回:
布尔值
另请参阅
Index.is_monotonic_decreasing
检查数值是否相等或递减。
示例
>>> pd.Index([1, 2, 3]).is_monotonic_increasing
True
>>> pd.Index([1, 2, 2]).is_monotonic_increasing
True
>>> pd.Index([1, 3, 2]).is_monotonic_increasing
False
pandas.Index.is_monotonic_decreasing
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_monotonic_decreasing.html
property Index.is_monotonic_decreasing
返回一个布尔值,指示数值是否相等或递减。
返回:
布尔值
另请参阅
Index.is_monotonic_increasing
检查数值是否相等或递减。
示例
>>> pd.Index([3, 2, 1]).is_monotonic_decreasing
True
>>> pd.Index([3, 2, 2]).is_monotonic_decreasing
True
>>> pd.Index([3, 1, 2]).is_monotonic_decreasing
False
pandas.Index.is_unique
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_unique.html
Index.is_unique
返回索引是否具有唯一值。
返回:
布尔值
参见
Index.has_duplicates
检查是否具有重复值的反方法。
示例
>>> idx = pd.Index([1, 5, 7, 7])
>>> idx.is_unique
False
>>> idx = pd.Index([1, 5, 7])
>>> idx.is_unique
True
>>> idx = pd.Index(["Watermelon", "Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.is_unique
False
>>> idx = pd.Index(["Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.is_unique
True
pandas.Index.has_duplicates
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.has_duplicates.html
property Index.has_duplicates
检查索引是否具有重复值。
返回:
布尔值
索引是否具有重复值。
参见
Index.is_unique
检查是否具有唯一值的反方法。
示例
>>> idx = pd.Index([1, 5, 7, 7])
>>> idx.has_duplicates
True
>>> idx = pd.Index([1, 5, 7])
>>> idx.has_duplicates
False
>>> idx = pd.Index(["Watermelon", "Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.has_duplicates
True
>>> idx = pd.Index(["Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.has_duplicates
False
pandas.Index.hasnans
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.hasnans.html
Index.hasnans
如果存在任何 NaN,则返回 True。
启用各种性能优化。
返回值:
布尔值
示例
>>> s = pd.Series([1, 2, 3], index=['a', 'b', None])
>>> s
a 1
b 2
None 3
dtype: int64
>>> s.index.hasnans
True
pandas.Index.dtype
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.dtype.html
Index.dtype
返回底层数据的 dtype 对象。
Examples
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.dtype
dtype('int64')
pandas.Index.inferred_type
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.inferred_type.html
Index.inferred_type
返回从值推断的类型的字符串。
示例
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.inferred_type
'integer'
pandas.Index.shape
pandas.pydata.org/docs/reference/api/pandas.Index.shape.html
property Index.shape
返回基础数据的形状的元组。
示例
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.shape
(3,)
pandas.Index.name
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.name.html
property Index.name
返回索引或多级索引的名称。
例子
>>> idx = pd.Index([1, 2, 3], name='x')
>>> idx
Index([1, 2, 3], dtype='int64', name='x')
>>> idx.name
'x'
pandas.Index.names
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.names.html
property Index.names
pandas.Index.nbytes
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.nbytes.html
property Index.nbytes
返回底层数据的字节数。
示例
对于 Series:
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.nbytes
24
对于 Index:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.nbytes
24
pandas.Index.ndim
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.ndim.html
property Index.ndim
数据底层维度的数量,根据定义为 1。
例子
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.ndim
1
对于索引:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.ndim
1
pandas.Index.size
property Index.size
返回基础数据中的元素数量。
示例
对于 Series:
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.size
3
对于 Index:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.size
3
pandas.Index.empty
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.empty.html
property Index.empty
pandas.Index.T
property Index.T
返回转置,根据定义是自身。
示例
对于 Series:
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.T
0 Ant
1 Bear
2 Cow
dtype: object
对于 Index:
>>> idx = pd.Index([1, 2, 3])
>>> idx.T
Index([1, 2, 3], dtype='int64')
pandas.Index.memory_usage
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.memory_usage.html
Index.memory_usage(deep=False)
值的内存使用情况。
参数:
深入布尔值,默认为 False
深入分析数据,查询对象的数据类型以了解系统级内存消耗。
返回:
使用的字节
另请参阅
数组元素消耗的总字节数。
注意
内存使用情况不包括由于深度为 False 或在 PyPy 上使用时不是数组组成部分的元素消耗的内存。
例子
>>> idx = pd.Index([1, 2, 3])
>>> idx.memory_usage()
24
pandas.Index.all
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.all.html
Index.all(*args, **kwargs)
返回所有元素是否为 Truthy。
参数:
*args
为了与 numpy 兼容而需要。
**kwargs
为了与 numpy 兼容而需要。
返回值:
布尔值或类数组(如果指定了轴)
单个元素的类数组可以转换为布尔值。
另请参阅
返回索引中是否有任何元素为 True。
返回 Series 中是否有任何元素为 True。
返回 Series 中所有元素是否为 True。
注意
不是数字(NaN)、正无穷大和负无穷大会评估为 True,因为它们不等于零。
示例
True,因为非零整数被视为 True。
>>> pd.Index([1, 2, 3]).all()
True
False,因为0
被视为 False。
>>> pd.Index([0, 1, 2]).all()
False
pandas.Index.any
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.any.html
Index.any(*args, **kwargs)
返回任何元素是否为真值。
参数:
*args
与 numpy 兼容性所需。
**kwargs
与 numpy 兼容性所需。
返回:
如果指定了轴,则返回 bool 或类似数组。
单个元素类似数组可以转换为 bool。
另请参阅
Index.all
返回所有元素是否为 True。
Series.all
返回所有元素是否为 True。
注意事项
非数字(NaN)、正无穷和负无穷评估为 True,因为它们不等于零。
示例
>>> index = pd.Index([0, 1, 2])
>>> index.any()
True
>>> index = pd.Index([0, 0, 0])
>>> index.any()
False
pandas.Index.argmin
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.argmin.html
Index.argmin(axis=None, skipna=True, *args, **kwargs)
返回系列中最小值的整数位置。
如果在多个位置达到最小值,则返回第一行位置。
参数:
axis
未使用。与 DataFrame 兼容性所需的参数。
skipnabool,默认为 True
在显示结果时排除 NA/null 值。
***args, kwargs
用于与 NumPy 兼容性的额外参数和关键字。
返回:
int
最小值的行位置。
另请参阅
Series.argmin
返回最小值的位置。
Series.argmax
返回最大值的位置。
用于 numpy 数组的等效方法。
Series.idxmax
返回最大值的索引标签。
Series.idxmin
返回最小值的索引标签。
示例
考虑包含谷物热量的数据集
>>> s = pd.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0,
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0})
>>> s
Corn Flakes 100.0
Almond Delight 110.0
Cinnamon Toast Crunch 120.0
Cocoa Puff 110.0
dtype: float64
>>> s.argmax()
2
>>> s.argmin()
0
最大谷物热量是第三个元素,最小谷物热量是第一个元素,因为系列是从零开始索引的。
pandas.Index.argmax
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.argmax.html
Index.argmax(axis=None, skipna=True, *args, **kwargs)
返回 Series 中最大值的 int 位置。
如果最大值在多个位置达到,则返回第一行位置。
参数:
轴
未使用。与 DataFrame 兼容所需的参数。
skipna布尔值,默认为 True
在显示结果时排除 NA/null 值。
***args, kwargs
为了与 NumPy 兼容,还有其他参数和关键词。
返回:
int
最大值的行位置。
另请参阅
Series.argmax
返回最大值的位置。
Series.argmin
返回最小值的位置。
numpy 数组的等效方法。
Series.idxmax
返回最大值的索引标签。
Series.idxmin
返回最小值的索引标签。
示例
考虑包含谷物热量的数据集
>>> s = pd.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0,
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0})
>>> s
Corn Flakes 100.0
Almond Delight 110.0
Cinnamon Toast Crunch 120.0
Cocoa Puff 110.0
dtype: float64
>>> s.argmax()
2
>>> s.argmin()
0
最大谷物热量是第三个元素,最小谷物热量是第一个元素,因为 Series 是从零开始索引的。
pandas.Index.copy
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.copy.html
Index.copy(name=None, deep=False)
复制此对象。
在新对象上设置名称。
参数:
name 标签,可选
为新对象设置名称。
deep 布尔值,默认为 False
返回:
索引
索引引用新对象,该对象是此对象的副本。
注意
在大多数情况下,使用deep
应该没有功能上的区别,但如果传递了deep
,它将尝试深度复制。
示例
>>> idx = pd.Index(['a', 'b', 'c'])
>>> new_idx = idx.copy()
>>> idx is new_idx
False
pandas.Index.delete
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.delete.html
Index.delete(loc)
创建一个删除了传递位置的新索引。
参数:
loc整数或整数列表
将要删除的项目的位置。使用位置列表一次删除多个值。
返回:
索引
与 self 相同的类型,除了 RangeIndex。
另请参见
从 NumPy 数组(ndarray)中删除任何行和列。
示例
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx.delete(1)
Index(['a', 'c'], dtype='object')
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx.delete([0, 2])
Index(['b'], dtype='object')
pandas.Index.drop
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.drop.html
Index.drop(labels, errors='raise')
用传递的标签列表创建新的 Index,并删除它们。
Parameters:
labelsarray-like or scalar
errors, default ‘raise’
如果为‘ignore’,则抑制错误,现有标签将被删除。
Returns:
Index
与 self 相同类型,除了 RangeIndex 外。
Raises:
KeyError
如果在所选轴中未找到所有标签
Examples
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx.drop(['a'])
Index(['b', 'c'], dtype='object')
pandas.Index.drop_duplicates
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.drop_duplicates.html
Index.drop_duplicates(*, keep='first')
返回删除重复值的索引。
参数:
keep{'first','last',False
},默认为 'first'
-
‘first’:除了第一次出现的重复值之外,删除重复值。
-
‘last’:除了最后一个出现的重复值之外,删除重复值。
-
False
:删除所有重复值。
返回:
索引
另请参阅
Series.drop_duplicates
Series 上的等效方法。
DataFrame.drop_duplicates
DataFrame 上的等效方法。
Index.duplicated
索引上的相关方法,指示重复的索引值。
示例
生成具有重复值的 pandas.Index。
>>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'])
keep 参数控制要删除的重复值。值 'first' 保留每组重复条目的第一个出现。keep 的默认值为 'first'。
>>> idx.drop_duplicates(keep='first')
Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object')
值 'last' 保留每组重复条目的最后一个出现。
>>> idx.drop_duplicates(keep='last')
Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object')
值 False
丢弃所有重复条目集。
>>> idx.drop_duplicates(keep=False)
Index(['cow', 'beetle', 'hippo'], dtype='object')
pandas.Index.duplicated
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.duplicated.html
Index.duplicated(keep='first')
指示重复的索引值。
在结果数组中,重复值表示为 True
值。可以指示所有重复值,除了第一个,或除了重复值的最后一个发生的所有值。
参数:
keep,默认为 ‘first’
在一组重复值中,要标记为缺失的值或值。
-
‘first’:将重复项标记为
True
,除了第一次出现的情况。 -
‘last’:将重复项标记为
True
,除了最后一次出现的情况。 -
False
:将所有重复项标记为True
。
返回:
np.ndarray[bool]
另请参见
Series.duplicated
在 pandas.Series 上的等效方法。
DataFrame.duplicated
DataFrame 上的等效方法。
Index.drop_duplicates
从索引中删除重复值。
示例
默认情况下,对于每组重复值,第一次出现的设置为 False,其他所有值设置为 True:
>>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama'])
>>> idx.duplicated()
array([False, False, True, False, True])
这相当于
>>> idx.duplicated(keep='first')
array([False, False, True, False, True])
通过使用 'last',每组重复值的最后一次出现设置为 False,其他所有值设置为 True:
>>> idx.duplicated(keep='last')
array([ True, False, True, False, False])
通过将 keep
设置为 False
,所有重复项都是 True:
>>> idx.duplicated(keep=False)
array([ True, False, True, False, True])
pandas.Index.equals
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.equals.html
Index.equals(other)
确定两个索引对象是否相等。
正在比较的内容包括:
-
索引对象内的元素。
-
索引对象内元素的顺序。
参数:
other 任意
用于比较的其他对象。
返回:
布尔值
如果“other”是一个索引,并且它的元素和顺序与调用索引相同,则为 True;否则为 False。
示例
>>> idx1 = pd.Index([1, 2, 3])
>>> idx1
Index([1, 2, 3], dtype='int64')
>>> idx1.equals(pd.Index([1, 2, 3]))
True
内部元素进行比较
>>> idx2 = pd.Index(["1", "2", "3"])
>>> idx2
Index(['1', '2', '3'], dtype='object')
>>> idx1.equals(idx2)
False
比较顺序
>>> ascending_idx = pd.Index([1, 2, 3])
>>> ascending_idx
Index([1, 2, 3], dtype='int64')
>>> descending_idx = pd.Index([3, 2, 1])
>>> descending_idx
Index([3, 2, 1], dtype='int64')
>>> ascending_idx.equals(descending_idx)
False
不比较数据类型
>>> int64_idx = pd.Index([1, 2, 3], dtype='int64')
>>> int64_idx
Index([1, 2, 3], dtype='int64')
>>> uint64_idx = pd.Index([1, 2, 3], dtype='uint64')
>>> uint64_idx
Index([1, 2, 3], dtype='uint64')
>>> int64_idx.equals(uint64_idx)
True
pandas.Index.factorize
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.factorize.html
Index.factorize(sort=False, use_na_sentinel=True)
将对象编码为枚举类型或分类变量。
当所有重要的是识别不同值时,此方法非常有用以获取数组的数值表示。factorize 既可以作为顶级函数pandas.factorize()
,也可以作为方法Series.factorize()
和Index.factorize()
。
参数:
sort布尔值,默认为 False
对唯一值进行排序并洗牌代码以保持关系。
use_na_sentinel布尔值,默认为 True
如果为 True,则 NaN 值将使用标志值-1。如果为 False,则 NaN 值将被编码为非负整数,并且不会从值的唯一值中删除 NaN。
新版本 1.5.0 中新增。
返回:
codes ndarray
一个整数 ndarray,它是对 uniques 的索引器。 uniques.take(codes)
的值与 values 相同。
uniques ndarray、索引或 Categorical
唯一的有效值。当值为 Categorical 时,uniques 是一个 Categorical。当值为其他某些 pandas 对象时,将返回一个索引。否则,将返回一个 1-D 的 ndarray。
注意
即使值中存在缺失值,uniques 也不会包含它的条目。
另请参阅
cut
将连续值数组离散化。
unique
在数组中查找唯一值。
注意
更多示例,请参阅用户指南。
示例
这些示例都显示 factorize 作为一个顶级方法,例如pd.factorize(values)
。对于类似Series.factorize()
的方法,结果是相同的。
>>> codes, uniques = pd.factorize(np.array(['b', 'b', 'a', 'c', 'b'], dtype="O"))
>>> codes
array([0, 0, 1, 2, 0])
>>> uniques
array(['b', 'a', 'c'], dtype=object)
使用sort=True
,uniques 将被排序,codes 将被洗牌,以保持关系。
>>> codes, uniques = pd.factorize(np.array(['b', 'b', 'a', 'c', 'b'], dtype="O"),
... sort=True)
>>> codes
array([1, 1, 0, 2, 1])
>>> uniques
array(['a', 'b', 'c'], dtype=object)
当use_na_sentinel=True
(默认值)时,缺失值在代码中用标志值-1
表示,并且缺失值不包含在 uniques 中。
>>> codes, uniques = pd.factorize(np.array(['b', None, 'a', 'c', 'b'], dtype="O"))
>>> codes
array([ 0, -1, 1, 2, 0])
>>> uniques
array(['b', 'a', 'c'], dtype=object)
到目前为止,我们只对列表进行了因式分解(这些列表在内部被强制转换为 NumPy 数组)。当对 pandas 对象进行因式分解时,uniques 的类型将不同。对于 Categoricals,将返回一个 Categorical。
>>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c'])
>>> codes, uniques = pd.factorize(cat)
>>> codes
array([0, 0, 1])
>>> uniques
['a', 'c']
Categories (3, object): ['a', 'b', 'c']
注意,尽管'b'不在'cat.values'中,但'b'确实在'uniques.categories'中。
对于所有其他 pandas 对象,将返回适当类型的索引。
>>> cat = pd.Series(['a', 'a', 'c'])
>>> codes, uniques = pd.factorize(cat)
>>> codes
array([0, 0, 1])
>>> uniques
Index(['a', 'c'], dtype='object')
如果值中包含 NaN,并且我们希望在值的唯一值中包含 NaN,则可以通过设置use_na_sentinel=False
来实现。
>>> values = np.array([1, 2, 1, np.nan])
>>> codes, uniques = pd.factorize(values) # default: use_na_sentinel=True
>>> codes
array([ 0, 1, 0, -1])
>>> uniques
array([1., 2.])
>>> codes, uniques = pd.factorize(values, use_na_sentinel=False)
>>> codes
array([0, 1, 0, 2])
>>> uniques
array([ 1., 2., nan])
pandas.Index.identical
pandas.pydata.org/docs/reference/api/pandas.Index.identical.html
final Index.identical(other)
类似于 equals,但检查对象属性和类型是否也相等。
返回:
布尔值
如果两个索引对象具有相同类型和相同元素,则返回 True,否则返回 False。
示例
>>> idx1 = pd.Index(['1', '2', '3'])
>>> idx2 = pd.Index(['1', '2', '3'])
>>> idx2.identical(idx1)
True
>>> idx1 = pd.Index(['1', '2', '3'], name="A")
>>> idx2 = pd.Index(['1', '2', '3'], name="B")
>>> idx2.identical(idx1)
False
pandas.Index.insert
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.insert.html
Index.insert(loc, item)
在指定位置插入新项目创建新索引。
遵循 Python numpy.insert 对负值的语义。
参数:
loc整数
item对象
返回:
索引
示例
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx.insert(1, 'x')
Index(['a', 'x', 'b', 'c'], dtype='object')
pandas.Index.is_
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_.html
final Index.is_(other)
更灵活,更快速的检查,类似于is
,但通过视图工作。
注意:这与Index.identical()
不同,后者还检查元数据是否相同。
参数:
otherobject
要比较的其他对象。
返回:
布尔值
如果两者具有相同的基础数据,则为 True,否则为 False。
另请参见
Index.identical
类似于Index.is_
,但也检查元数据。
示例
>>> idx1 = pd.Index(['1', '2', '3'])
>>> idx1.is_(idx1.view())
True
>>> idx1.is_(idx1.copy())
False
pandas.Index.is_boolean
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_boolean.html
final Index.is_boolean()
检查索引是否仅由布尔值组成。
自版本 2.0.0 起已弃用:请使用 pandas.api.types.is_bool_dtype。
返回:
布尔值
索引是否仅由布尔值组成。
另请参阅
is_integer
检查索引是否仅由整数组成(已弃用)。
is_floating
检查索引是否为浮点类型(已弃用)。
is_numeric
检查索引是否仅由数值数据组成(已弃用)。
is_object
检查索引是否为对象数据类型(已弃用)。
is_categorical
检查索引是否包含分类数据。
is_interval
检查索引是否包含区间对象(已弃用)。
示例
>>> idx = pd.Index([True, False, True])
>>> idx.is_boolean()
True
>>> idx = pd.Index(["True", "False", "True"])
>>> idx.is_boolean()
False
>>> idx = pd.Index([True, False, "True"])
>>> idx.is_boolean()
False
pandas.Index.is_categorical
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_categorical.html
final Index.is_categorical()
检查索引是否包含分类数据。
自版本 2.0.0 起已弃用:改用 isinstance(index.dtype, pd.CategoricalDtype)。
返回:
布尔值
如果索引是分类的,则为 True。
另请参阅
CategoricalIndex
用于分类数据的索引。
is_boolean
检查索引是否仅包含布尔值(已弃用)。
is_integer
检查索引是否仅包含整数(已弃用)。
is_floating
检查索引是否为浮点类型(已弃用)。
is_numeric
检查索引是否仅包含数值数据(已弃用)。
is_object
检查索引是否为对象数据类型(已弃用)。
is_interval
检查索引是否包含区间对象(已弃用)。
示例
>>> idx = pd.Index(["Watermelon", "Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.is_categorical()
True
>>> idx = pd.Index([1, 3, 5, 7])
>>> idx.is_categorical()
False
>>> s = pd.Series(["Peter", "Victor", "Elisabeth", "Mar"])
>>> s
0 Peter
1 Victor
2 Elisabeth
3 Mar
dtype: object
>>> s.index.is_categorical()
False
pandas.Index.is_floating
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_floating.html
final Index.is_floating()
检查索引是否为浮点类型。
自版本 2.0.0 起已弃用:请使用 pandas.api.types.is_float_dtype 代替
索引可能仅包含浮点数、NaN 或浮点数、整数或 NaN 的混合。
返回:
布尔值
索引是否仅包含浮点数、NaN 或浮点数、整数或 NaN 的混合。
另请参阅
检查索引是否仅包含布尔值(已弃用)。
检查索引是否仅包含整数(已弃用)。
检查索引是否仅包含数值数据(已弃用)。
检查索引是否为对象数据类型(已弃用)。
检查索引是否包含分类数据(已弃用)。
检查索引是否包含区间对象(已弃用)。
示例
>>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
>>> idx.is_floating()
True
>>> idx = pd.Index([1.0, 2.0, np.nan, 4.0])
>>> idx.is_floating()
True
>>> idx = pd.Index([1, 2, 3, 4, np.nan])
>>> idx.is_floating()
True
>>> idx = pd.Index([1, 2, 3, 4])
>>> idx.is_floating()
False
pandas.Index.is_integer
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_integer.html
final Index.is_integer()
检查索引是否仅由整数组成。
自 2.0.0 版本弃用:请使用 pandas.api.types.is_integer_dtype 代替。
返回:
布尔值
索引是否仅由整数组成。
另请参阅
检查索引是否仅由布尔值组成(已弃用)。
检查索引是否为浮点类型(已弃用)。
检查索引是否仅由数字数据组成(已弃用)。
检查索引是否为对象数据类型(已弃用)。
检查索引是否持有分类数据(已弃用)。
检查索引是否持有区间对象(已弃用)。
示例
>>> idx = pd.Index([1, 2, 3, 4])
>>> idx.is_integer()
True
>>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
>>> idx.is_integer()
False
>>> idx = pd.Index(["Apple", "Mango", "Watermelon"])
>>> idx.is_integer()
False
pandas.Index.is_interval
pandas.pydata.org/docs/reference/api/pandas.Index.is_interval.html
final Index.is_interval()
检查索引是否包含区间对象。
自版本 2.0.0 起已弃用:请改用 isinstance(index.dtype, pd.IntervalDtype)。
返回:
布尔值
索引是否包含区间对象。
另请参阅
IntervalIndex
区间对象的索引。
is_boolean
检查索引是否仅由布尔值组成(已弃用)。
is_integer
检查索引是否仅由整数组成(已弃用)。
is_floating
检查索引是否为浮点类型(已弃用)。
is_numeric
检查索引是否仅由数值数据组成(已弃用)。
is_object
检查索引是否为对象数据类型(已弃用)。
is_categorical
检查索引是否包含分类数据(已弃用)。
示例
>>> idx = pd.Index([pd.Interval(left=0, right=5),
... pd.Interval(left=5, right=10)])
>>> idx.is_interval()
True
>>> idx = pd.Index([1, 3, 5, 7])
>>> idx.is_interval()
False
pandas.Index.is_numeric
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_numeric.html
final Index.is_numeric()
检查索引是否仅包含数值数据。
自版本 2.0.0 弃用:请使用 pandas.api.types.is_numeric_dtype 代替。
返回:
布尔值
索引是否仅包含数值数据。
另请参阅
检查索引是否仅包含布尔值(已弃用)。
检查索引是否仅包含整数(已弃用)。
检查索引是否为浮点类型(已弃用)。
检查索引是否为对象数据类型(已弃用)。
检查索引是否持有分类数据(已弃用)。
检查索引是否持有区间对象(已弃用)。
示例
>>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
>>> idx.is_numeric()
True
>>> idx = pd.Index([1, 2, 3, 4.0])
>>> idx.is_numeric()
True
>>> idx = pd.Index([1, 2, 3, 4])
>>> idx.is_numeric()
True
>>> idx = pd.Index([1, 2, 3, 4.0, np.nan])
>>> idx.is_numeric()
True
>>> idx = pd.Index([1, 2, 3, 4.0, np.nan, "Apple"])
>>> idx.is_numeric()
False
pandas.Index.is_object
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.is_object.html
final Index.is_object()
检查索引是否为对象数据类型。
自版本 2.0.0 起已弃用:请使用 pandas.api.types.is_object_dtype 代替。
返回:
布尔值
索引是否为对象数据类型。
另请参阅
is_boolean
检查索引是否仅由布尔值组成(已弃用)。
is_integer
检查索引是否仅由整数组成(已弃用)。
is_floating
检查索引是否为浮点类型(已弃用)。
is_numeric
检查索引是否仅由数值数据组成(已弃用)。
is_categorical
检查索引是否持有分类数据(已弃用)。
is_interval
检查索引是否持有间隔对象(已弃用)。
例子
>>> idx = pd.Index(["Apple", "Mango", "Watermelon"])
>>> idx.is_object()
True
>>> idx = pd.Index(["Apple", "Mango", 2.0])
>>> idx.is_object()
True
>>> idx = pd.Index(["Watermelon", "Orange", "Apple",
... "Watermelon"]).astype("category")
>>> idx.is_object()
False
>>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
>>> idx.is_object()
False
pandas.Index.min
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.min.html
Index.min(axis=None, skipna=True, *args, **kwargs)
返回索引的最小值。
参数:
axis
为了与 Series 保持一致的虚拟参数。
skipnabool, 默认为 True
在显示结果时排除 NA/null 值。
***args, kwargs
为了与 NumPy 兼容而提供的额外参数和关键字。
返回:
标量
最小值。
另请参见
Index.max
返回对象的最大值。
Series.min
返回 Series 中的最小值。
DataFrame.min
返回 DataFrame 中的最小值。
示例
>>> idx = pd.Index([3, 2, 1])
>>> idx.min()
1
>>> idx = pd.Index(['c', 'b', 'a'])
>>> idx.min()
'a'
对于 MultiIndex,最小值按词典顺序确定。
>>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
>>> idx.min()
('a', 1)
pandas.Index.max
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.max.html
Index.max(axis=None, skipna=True, *args, **kwargs)
返回索引的最大值。
参数:
axisint, 可选
为了与 NumPy 兼容。仅允许 0 或 None。
skipnabool, 默认 True
在显示结果时排除 NA/null 值。
***args, kwargs
与 NumPy 兼容的附加参数和关键字。
返回:
标量
最大值。
另请参阅
Index.min
返回索引中的最小值。
Series.max
返回 Series 中的最大值。
DataFrame.max
返回 DataFrame 中的最大值。
示例
>>> idx = pd.Index([3, 2, 1])
>>> idx.max()
3
>>> idx = pd.Index(['c', 'b', 'a'])
>>> idx.max()
'c'
对于 MultiIndex,最大值是按词典顺序确定的。
>>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
>>> idx.max()
('b', 2)
pandas.Index.reindex
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.reindex.html
Index.reindex(target, method=None, level=None, limit=None, tolerance=None)
Create index with target’s values.
Parameters:
targetan iterable
method, optional
-
default: exact matches only.
-
pad / ffill: find the PREVIOUS index value if no exact match.
-
backfill / bfill: use NEXT index value if no exact match
-
nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value.
levelint, optional
Level of multiindex.
limitint, optional
Maximum number of consecutive labels in target
to match for inexact matches.
toleranceint or float, optional
Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations must satisfy the equation abs(index[indexer] - target) <= tolerance
.
Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type.
Returns:
new_indexpd.Index
Resulting index.
indexernp.ndarray[np.intp] or None
Indices of output values in original index.
Raises:
TypeError
If method
passed along with level
.
ValueError
If non-unique multi-index
ValueError
If non-unique index and method
or limit
passed.
See also
Series.reindex
Conform Series to new index with optional filling logic.
DataFrame.reindex
Conform DataFrame to new index with optional filling logic.
Examples
>>> idx = pd.Index(['car', 'bike', 'train', 'tractor'])
>>> idx
Index(['car', 'bike', 'train', 'tractor'], dtype='object')
>>> idx.reindex(['car', 'bike'])
(Index(['car', 'bike'], dtype='object'), array([0, 1]))
pandas.Index.rename
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.rename.html
Index.rename(name, *, inplace=False)
修改索引或 MultiIndex 名称。
能够不通过级别设置新名称。默认返回新的索引。名称的长度必须与 MultiIndex 中的级别数相匹配。
参数:
name标签或标签列表
要设置的名称。
inplace布尔值,默认为 False
直接修改对象,而不是创建新的 Index 或 MultiIndex。
返回:
索引或 None
与调用者相同类型,如果 inplace=True
则为 None。
另请参阅
Index.set_names
能够通过级别部分地设置新名称。
示例
>>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score')
>>> idx.rename('grade')
Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')
>>> idx = pd.MultiIndex.from_product([['python', 'cobra'],
... [2018, 2019]],
... names=['kind', 'year'])
>>> idx
MultiIndex([('python', 2018),
('python', 2019),
( 'cobra', 2018),
( 'cobra', 2019)],
names=['kind', 'year'])
>>> idx.rename(['species', 'year'])
MultiIndex([('python', 2018),
('python', 2019),
( 'cobra', 2018),
( 'cobra', 2019)],
names=['species', 'year'])
>>> idx.rename('species')
Traceback (most recent call last):
TypeError: Must pass list-like as `names`.
pandas.Index.repeat
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.repeat.html
Index.repeat(repeats, axis=None)
重复索引元素。
返回一个新的索引,其中当前索引的每个元素连续重复指定的次数。
参数:
repeats 整数或整数数组
每个元素的重复次数。这应该是一个非负整数。重复 0 次将返回一个空索引。
axis None
必须为 None
。没有效果,但为了与 numpy 兼容而被接受。
返回:
索引
新创建的重复元素的索引。
另请参见
Series.repeat
Series 的等效函数。
与 numpy.ndarray
类似的方法。
示例
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx
Index(['a', 'b', 'c'], dtype='object')
>>> idx.repeat(2)
Index(['a', 'a', 'b', 'b', 'c', 'c'], dtype='object')
>>> idx.repeat([1, 2, 3])
Index(['a', 'b', 'b', 'c', 'c', 'c'], dtype='object')
pandas.Index.where
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.where.html
final Index.where(cond, other=None)
替换条件为假的值。
替换来自其他。
参数:
cond与 self 长度相同的布尔数组
选择上的条件。
other标量或数组样式,默认为 None
如果条件为 False,则替换。
返回:
pandas.Index
从 other 替换为假条件的 self 的副本。
另请参阅
Series.where
Series 的相同方法。
DataFrame.where
DataFrame 的相同方法。
示例
>>> idx = pd.Index(['car', 'bike', 'train', 'tractor'])
>>> idx
Index(['car', 'bike', 'train', 'tractor'], dtype='object')
>>> idx.where(idx.isin(['car', 'train']), 'other')
Index(['car', 'other', 'train', 'other'], dtype='object')
pandas.Index.take
pandas.pydata.org/docs/reference/api/pandas.Index.take.html
的原文。
Index.take(indices, axis=0, allow_fill=True, fill_value=None, **kwargs)
返回由索引选定的值的新索引。
用于与 numpy 数组的内部兼容性。
参数:
indices数组样式
需要取出的索引。
axisint,可选
选择值的轴,始终为 0。
allow_fillbool,默认为 True
fill_value标量,默认为None
如果allow_fill=True
且fill_value
不为None
,则指定为-1 的索引被视为 NA。如果索引不包含 NA,则引发ValueError
。
返回:
索引
由给定索引处的元素组成的索引。类型与自身相同,除了RangeIndex
。
另请参阅
返回一个由给定索引处的元素组成的数组。
示例
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx.take([2, 2, 1, 2])
Index(['c', 'c', 'b', 'c'], dtype='object')
pandas.Index.putmask
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.putmask.html
Index.putmask(mask, value)
返回一个新的索引,其值根据掩码设置。
返回:
索引
另请参阅
numpy.ndarray.putmask
根据条件和输入值改变数组元素。
示例
>>> idx1 = pd.Index([1, 2, 3])
>>> idx2 = pd.Index([5, 6, 7])
>>> idx1.putmask([True, False, False], idx2)
Index([5, 2, 3], dtype='int64')
pandas.Index.unique
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.unique.html
Index.unique(level=None)
返回索引中的唯一值。
唯一值按出现顺序返回,不进行排序。
参数:
级别整数或可散列,可选
仅返回指定级别的值(用于多级索引)。如果是整数,则按整数位置获取级别,否则按级别名称获取。
返回:
索引
另请参阅
unique
该列中唯一值的 numpy 数组。
Series.unique
返回 Series 对象的唯一值。
示例
>>> idx = pd.Index([1, 1, 2, 3, 3])
>>> idx.unique()
Index([1, 2, 3], dtype='int64')
pandas.Index.nunique
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.nunique.html
Index.nunique(dropna=True)
返回对象中唯一元素的数量。
默认情况下排除 NA 值。
参数:
dropna 布尔值,默认为 True
不包括 NaN 在内的计数。
返回:
整数
另请参阅
DataFrame 的 nunique 方法。
计算 Series 中非 NA/null 观测值的数量。
示例
>>> s = pd.Series([1, 3, 5, 7, 7])
>>> s
0 1
1 3
2 5
3 7
4 7
dtype: int64
>>> s.nunique()
4
pandas.Index.value_counts
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.value_counts.html
Index.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)
返回一个包含唯一值计数的系列。
结果对象将按降序排列,使第一个元素是最频繁出现的元素。默认情况下排除 NA 值。
参数:
normalize布尔值,默认为 False
如果为 True,则返回的对象将包含唯一值的相对频率。
sort布尔值,默认为 True
当为 True 时按频率排序。当为 False 时保留数据的顺序。
ascending布尔值,默认为 False
按升序排序。
bins整数,可选
而不是计数值,将它们分组到半开区间,这对于pd.cut
来说很方便,只适用于数值数据。
dropna布尔值,默认为 True
不包括 NaN 的计数。
返回:
系列
另请参阅
系列中的非 NA 元素数。
数据帧中的非 NA 元素数。
数据帧上的等效方法。
示例
>>> index = pd.Index([3, 1, 2, 3, 4, np.nan])
>>> index.value_counts()
3.0 2
1.0 1
2.0 1
4.0 1
Name: count, dtype: int64
当 normalize 设置为 True 时,通过将所有值除以值的总和来返回相对频率。
>>> s = pd.Series([3, 1, 2, 3, 4, np.nan])
>>> s.value_counts(normalize=True)
3.0 0.4
1.0 0.2
2.0 0.2
4.0 0.2
Name: proportion, dtype: float64
bins
对于从连续变量到分类变量的转换,箱可以很有用;不是计算值的唯一出现次数,而是将索引分成指定数量的半开箱。
>>> s.value_counts(bins=3)
(0.996, 2.0] 2
(2.0, 3.0] 2
(3.0, 4.0] 1
Name: count, dtype: int64
dropna
当 dropna 设置为 False 时,我们还可以看到 NaN 索引值。
>>> s.value_counts(dropna=False)
3.0 2
1.0 1
2.0 1
4.0 1
NaN 1
Name: count, dtype: int64
pandas.Index.set_names
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.set_names.html
Index.set_names(names, *, level=None, inplace=False)
设置索引或多级索引名称。
能够部分设置新名称并按级别设置。
参数:
names标签、标签的列表或多级索引的类似字典
要设置的名称。
从版本 1.3.0 开始更改。
级别整数、标签或整数或标签的列表,可选
如果索引是多级索引,并且 names 不是类似字典,则设置级别(所有级别为 None)。否则级别必须为 None。
从版本 1.3.0 开始更改。
inplace布尔值,默认为 False
直接修改对象,而不是创建新的索引或多级索引。
返回:
索引或 None
与调用者相同类型,如果 inplace=True
则为 None。
另请参阅
Index.rename
能够不按级别设置新名称。
示例
>>> idx = pd.Index([1, 2, 3, 4])
>>> idx
Index([1, 2, 3, 4], dtype='int64')
>>> idx.set_names('quarter')
Index([1, 2, 3, 4], dtype='int64', name='quarter')
>>> idx = pd.MultiIndex.from_product([['python', 'cobra'],
... [2018, 2019]])
>>> idx
MultiIndex([('python', 2018),
('python', 2019),
( 'cobra', 2018),
( 'cobra', 2019)],
)
>>> idx = idx.set_names(['kind', 'year'])
>>> idx.set_names('species', level=0)
MultiIndex([('python', 2018),
('python', 2019),
( 'cobra', 2018),
( 'cobra', 2019)],
names=['species', 'year'])
在使用字典重命名级别时,不能传递级别。
>>> idx.set_names({'kind': 'snake'})
MultiIndex([('python', 2018),
('python', 2019),
( 'cobra', 2018),
( 'cobra', 2019)],
names=['snake', 'year'])
pandas.Index.droplevel
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.droplevel.html
final Index.droplevel(level=0)
返回请求级别被移除后的索引。
如果生成的索引仅剩下一个级别,结果将是索引类型,而不是多级索引。原始索引不会就地修改。
参数:
level整数、字符串或类似列表,默认为 0
如果给定了一个字符串,则必须是级别的名称。如果类似于列表,则元素必须是级别的名称或索引。
返回:
索引或多级索引
示例
>>> mi = pd.MultiIndex.from_arrays(
... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z'])
>>> mi
MultiIndex([(1, 3, 5),
(2, 4, 6)],
names=['x', 'y', 'z'])
>>> mi.droplevel()
MultiIndex([(3, 5),
(4, 6)],
names=['y', 'z'])
>>> mi.droplevel(2)
MultiIndex([(1, 3),
(2, 4)],
names=['x', 'y'])
>>> mi.droplevel('z')
MultiIndex([(1, 3),
(2, 4)],
names=['x', 'y'])
>>> mi.droplevel(['x', 'y'])
Index([5, 6], dtype='int64', name='z')
pandas.Index.fillna
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.fillna.html
Index.fillna(value=None, downcast=_NoDefault.no_default)
使用指定值填充 NA/NaN 值。
参数:
value 标量
用于填充空洞的标量值(例如 0)。此值不能是类似列表的对象。
downcast 字典,默认为 None
一个项目->数据类型的字典,如果可能的话,会尝试将其降级到适当的等效类型(例如,如果可能的话,将 float64 降级到 int64)。
自版本 2.1.0 起已弃用。
返回:
索引
另请参阅
DataFrame.fillna
填充 DataFrame 的 NaN 值。
Series.fillna
填充 Series 的 NaN 值。
示例
>>> idx = pd.Index([np.nan, np.nan, 3])
>>> idx.fillna(0)
Index([0.0, 0.0, 3.0], dtype='float64')
pandas.Index.dropna
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.dropna.html
Index.dropna(how='any')
返回没有 NA/NaN 值的索引。
参数:
how,默认为 ‘any’
如果索引是 MultiIndex,则在任何或所有级别为 NaN 时删除该值。
返回:
索引
示例
>>> idx = pd.Index([1, np.nan, 3])
>>> idx.dropna()
Index([1.0, 3.0], dtype='float64')
pandas.Index.isna
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.isna.html
final Index.isna()
检测缺失值。
返回一个布尔值相同大小的对象,指示值是否为 NA。诸如 None
、numpy.NaN
或 pd.NaT
等 NA 值被映射为 True
值。其他所有值都被映射为 False
值。诸如空字符串 ‘’ 或 numpy.inf
的字符不被视为 NA 值。
返回:
numpy.ndarray[bool]
一个布尔数组,指示我的值是否为 NA。
另请参见
Index.notna
isna 的布尔反转。
Index.dropna
省略具有缺失值的条目。
isna
顶级 isna。
Series.isna
在 Series 对象中检测缺失值。
示例
显示 pandas.Index 中的哪些条目是 NA。结果是一个数组。
>>> idx = pd.Index([5.2, 6.0, np.nan])
>>> idx
Index([5.2, 6.0, nan], dtype='float64')
>>> idx.isna()
array([False, False, True])
空字符串不被视为 NA 值。None 被视为 NA 值。
>>> idx = pd.Index(['black', '', 'red', None])
>>> idx
Index(['black', '', 'red', None], dtype='object')
>>> idx.isna()
array([False, False, False, True])
对于日期时间而言,NaT(Not a Time)被视为 NA 值。
>>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'),
... pd.Timestamp(''), None, pd.NaT])
>>> idx
DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'],
dtype='datetime64[ns]', freq=None)
>>> idx.isna()
array([False, True, True, True])
pandas.Index.notna
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.notna.html
final Index.notna()
检测已存在(非缺失)值。
返回一个布尔值大小相同的对象,指示值是否不是 NA。非缺失值映射为True
。诸如空字符串 ''
或 numpy.inf
之类的字符不视为 NA 值。NA 值,例如 None
或 numpy.NaN
,被映射为False
值。
返回:
numpy.ndarray[bool]
布尔数组指示哪些条目不是 NA。
另请参阅
Index.notnull
notna
的别名。
Index.isna
notna
的反义词。
notna
顶级 notna
。
示例
显示索引中非 NA 的条目。结果是一个数组。
>>> idx = pd.Index([5.2, 6.0, np.nan])
>>> idx
Index([5.2, 6.0, nan], dtype='float64')
>>> idx.notna()
array([ True, True, False])
空字符串不视为 NA 值。None
被视为 NA 值。
>>> idx = pd.Index(['black', '', 'red', None])
>>> idx
Index(['black', '', 'red', None], dtype='object')
>>> idx.notna()
array([ True, True, True, False])
pandas.Index.astype
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.astype.html
Index.astype(dtype, copy=True)
创建一个将值转换为指定 dtype 的索引。
新索引的类别由 dtype 确定。当转换不可能时,会引发 TypeError 异常。
参数:
dtypenumpy dtype 或 pandas 类型
请注意,任何有符号整数 dtype 都被视为'int64'
,任何无符号整数 dtype 都被视为'uint64'
,无论其大小如何。
copybool,默认为 True
默认情况下,astype 始终返回一个新分配的对象。如果 copy 设置为 False 并且满足 dtype 的内部要求,则使用原始数据创建新索引或返回原始索引。
返回:
索引
将值转换为指定 dtype 的索引。
示例
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.astype('float')
Index([1.0, 2.0, 3.0], dtype='float64')
pandas.Index.item
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.item.html
Index.item()
返回基础数据的第一个元素作为 Python 标量。
返回:
标量
Series 或 Index 的第一个元素。
引发:
值错误
如果数据不是长度 = 1。
示例
>>> s = pd.Series([1])
>>> s.item()
1
对于一个索引:
>>> s = pd.Series([1], index=['a'])
>>> s.index.item()
'a'
pandas.Index.map
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.map.html
Index.map(mapper, na_action=None)
使用输入映射或函数映射值。
参数:
mapper函数、字典或 Series
映射对应关系。
na_action
如果为 'ignore',则传播 NA 值,而不将它们传递给映射对应关系。
返回:
Union[Index, MultiIndex]
应用于索引的映射函数的输出。如果函数返回多于一个元素的元组,则将返回 MultiIndex。
示例
>>> idx = pd.Index([1, 2, 3])
>>> idx.map({1: 'a', 2: 'b', 3: 'c'})
Index(['a', 'b', 'c'], dtype='object')
使用函数进行映射:
>>> idx = pd.Index([1, 2, 3])
>>> idx.map('I am a {}'.format)
Index(['I am a 1', 'I am a 2', 'I am a 3'], dtype='object')
>>> idx = pd.Index(['a', 'b', 'c'])
>>> idx.map(lambda x: x.upper())
Index(['A', 'B', 'C'], dtype='object')
pandas.Index.ravel
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.ravel.html
final Index.ravel(order='C')
返回自身的视图。
返回值:
索引
另请参阅
返回一个扁平化的数组。
示例
>>> s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
>>> s.index.ravel()
Index(['a', 'b', 'c'], dtype='object')
pandas.Index.to_list
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.to_list.html
Index.to_list()
返回值的列表。
这些都是标量类型,即 Python 标量(对于 str、int、float)或 pandas 标量(对于 Timestamp/Timedelta/Interval/Period)
返回:
列表
另请参见
将数组作为 Python 标量的 a.ndim 级深度嵌套列表返回。
示例
对于 Series
>>> s = pd.Series([1, 2, 3])
>>> s.to_list()
[1, 2, 3]
对于索引:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.to_list()
[1, 2, 3]
pandas.Index.to_series
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.to_series.html
final Index.to_series(index=None, name=None)
创建一个既包含索引又包含值等于索引键的系列。
与 map 结合使用时,可根据索引返回索引器。
参数:
indexIndex,可选
结果系列的索引。如果为 None,则默认为原始索引。
namestr,可选
结果系列的名称。如果为 None,则默认为原始索引的名称。
返回:
系列
数据类型将基于索引值的类型。
另请参阅
Index.to_frame
将索引转换为数据帧。
Series.to_frame
将系列转换为数据帧。
示例
>>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
默认情况下,重用原始索引和原始名称。
>>> idx.to_series()
animal
Ant Ant
Bear Bear
Cow Cow
Name: animal, dtype: object
要强制使用新索引,请指定index
的新标签:
>>> idx.to_series(index=[0, 1, 2])
0 Ant
1 Bear
2 Cow
Name: animal, dtype: object
要覆盖结果列的名称,请指定name
:
>>> idx.to_series(name='zoo')
animal
Ant Ant
Bear Bear
Cow Cow
Name: zoo, dtype: object
pandas.Index.to_frame
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.to_frame.html
Index.to_frame(index=True, name=_NoDefault.no_default)
创建一个包含索引的列的 DataFrame。
参数:
index布尔值,默认为 True
将返回的 DataFrame 的索引设置为原始索引。
name对象,默认为 index.name
传递的名称应替代索引名称(如果有)。
返回:
DataFrame
包含原始索引数据的 DataFrame。
另请参阅
将索引转换为 Series。
将 Series 转换为 DataFrame。
示例
>>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
>>> idx.to_frame()
animal
animal
Ant Ant
Bear Bear
Cow Cow
默认情况下,会重用原始索引。要强制使用新索引:
>>> idx.to_frame(index=False)
animal
0 Ant
1 Bear
2 Cow
要覆盖结果列的名称,请指定 name:
>>> idx.to_frame(index=False, name='zoo')
zoo
0 Ant
1 Bear
2 Cow
pandas.Index.view
Index.view(cls=None)
pandas.Index.argsort
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.argsort.html
Index.argsort(*args, **kwargs)
返回排序后的索引的整数索引。
参数:
*args
传递给 numpy.ndarray.argsort。
**kwargs
传递给 numpy.ndarray.argsort。
返回:
np.ndarray[np.intp]
如果用作索引器,则会返回排序后的索引的整数索引。
另请参阅
NumPy 数组的类似方法。
Index.sort_values
返回索引的排序副本。
示例
>>> idx = pd.Index(['b', 'a', 'd', 'c'])
>>> idx
Index(['b', 'a', 'd', 'c'], dtype='object')
>>> order = idx.argsort()
>>> order
array([1, 0, 3, 2])
>>> idx[order]
Index(['a', 'b', 'c', 'd'], dtype='object')
pandas.Index.searchsorted
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.searchsorted.html
Index.searchsorted(value, side='left', sorter=None)
找到应该插入元素以保持顺序的索引。
找到插入到排序后的 Index self 中的索引,使得如果将 value 中的相应元素插入到索引之前,self 的顺序将被保留。
注意
索引 必须 是单调排序的,否则可能会返回错误的位置。Pandas 不 会为您检查此内容。
参数:
value类似数组或标量
要插入到 self 中的值。
side,可选
如果为 'left',则给出找到的第一个合适位置的索引。如果为 'right',则返回最后一个这样的索引。如果没有合适的索引,则返回 0 或 N(其中 N 是 self 的长度)。
sorter1-D 类似数组,可选
可选的整数索引数组,将 self 排序为升序。它们通常是np.argsort
的结果。
返回:
整数或整数数组
形状与 value 相同的标量或插入点数组。
另请参阅
sort_values
沿任一轴按值排序。
与 NumPy 中的类似方法。
注意
使用二分搜索找到所需的插入点。
示例
>>> ser = pd.Series([1, 2, 3])
>>> ser
0 1
1 2
2 3
dtype: int64
>>> ser.searchsorted(4)
3
>>> ser.searchsorted([0, 4])
array([0, 3])
>>> ser.searchsorted([1, 3], side='left')
array([0, 2])
>>> ser.searchsorted([1, 3], side='right')
array([1, 3])
>>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000']))
>>> ser
0 2000-03-11
1 2000-03-12
2 2000-03-13
dtype: datetime64[ns]
>>> ser.searchsorted('3/14/2000')
3
>>> ser = pd.Categorical(
... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True
... )
>>> ser
['apple', 'bread', 'bread', 'cheese', 'milk']
Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk']
>>> ser.searchsorted('bread')
1
>>> ser.searchsorted(['bread'], side='right')
array([3])
如果值不是单调排序的,则可能返回错误的位置:
>>> ser = pd.Series([2, 1, 3])
>>> ser
0 2
1 1
2 3
dtype: int64
>>> ser.searchsorted(1)
0 # wrong result, correct would be 1
pandas.Index.sort_values
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.sort_values.html
Index.sort_values(*, return_indexer=False, ascending=True, na_position='last', key=None)
返回索引的排序副本。
返回索引的排序副本,并可选择返回排序索引本身的索引。
参数:
return_indexer布尔值,默认为 False
是否应返回对索引进行排序的索引。
ascending布尔值,默认为 True
应该以升序排序索引值。
na_position,默认为 ‘last’
参数 ‘first’ 将 NaN 放在开头,‘last’ 将 NaN 放在末尾。
key可调用对象,可选
如果不是 None,请在排序之前将键函数应用于索引值。这类似于内置 sorted()
函数中的 key 参数,但有一个显着的区别,即此键函数应矢量化。它应该期望一个 Index
并返回一个相同形状的 Index
。
返回:
sorted_indexpandas.Index
索引的排序副本。
indexernumpy.ndarray,可选
索引本身按照其排序的索引。
另请参阅
对 Series 的值进行排序。
对 DataFrame 中的值进行排序。
示例
>>> idx = pd.Index([10, 100, 1, 1000])
>>> idx
Index([10, 100, 1, 1000], dtype='int64')
以升序排序值(默认行为)。
>>> idx.sort_values()
Index([1, 10, 100, 1000], dtype='int64')
以降序排序值,并获取 idx 的排序方式。
>>> idx.sort_values(ascending=False, return_indexer=True)
(Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))
pandas.Index.shift
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.shift.html
Index.shift(periods=1, freq=None)
按所需的时间频率增量移动索引。
此方法用于将类似日期时间的索引的值按指定的时间增量移动给定次数。
参数:
periodsint,默认为 1
要移动的周期数(或增量),可以为正数或负数。
freqpandas.DateOffset、pandas.Timedelta 或字符串,可选
频率增量以进行移动。如果为 None,则索引将按其自己的 freq 属性移动。偏移别名是有效的字符串,例如,'D','W','M'等。
返回:
pandas.Index
移动后的索引。
另请参见
Series.shift
移动 Series 的值。
注意事项
此方法仅针对类似日期时间的索引类实现,即 DatetimeIndex、PeriodIndex 和 TimedeltaIndex。
示例
将 2011 年前五个月的开始放入索引中。
>>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS')
>>> month_starts
DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01',
'2011-05-01'],
dtype='datetime64[ns]', freq='MS')
将索引向前移动 10 天。
>>> month_starts.shift(10, freq='D')
DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11',
'2011-05-11'],
dtype='datetime64[ns]', freq=None)
freq 的默认值是索引的 freq 属性,本示例中为'MS'(月初)。
>>> month_starts.shift(10)
DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01',
'2012-03-01'],
dtype='datetime64[ns]', freq='MS')
pandas.Index.append
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.append.html
Index.append(other)
将一系列索引选项添加在一起。
参数:
other索引或索引列表/元组
返回值:
索引
示例
>>> idx = pd.Index([1, 2, 3])
>>> idx.append(pd.Index([4]))
Index([1, 2, 3, 4], dtype='int64')
pandas.Index.join
final Index.join(other, *, how='left', level=None, return_indexers=False, sort=False)
计算 join_index 和 indexers,以使数据结构符合新索引。
参数:
otherIndex
how
levelint 或级别名称,默认为 None
return_indexersbool,默认为 False
sortbool,默认为 False
将结果索引中的连接键按词典顺序排序。如果为 False,则连接键的顺序取决于连接类型(how 关键字)。
返回:
join_index,(left_indexer,right_indexer)
示例
>>> idx1 = pd.Index([1, 2, 3])
>>> idx2 = pd.Index([4, 5, 6])
>>> idx1.join(idx2, how='outer')
Index([1, 2, 3, 4, 5, 6], dtype='int64')
pandas.Index.intersection
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.intersection.html
final Index.intersection(other, sort=False)
形成两个索引对象的交集。
这将返回一个新的索引,其中包含与索引和 other 共同的元素。
参数:
other 索引或类似数组
sort True、False 或 None,默认为 False
是否对结果索引进行排序。
-
None:对结果进行排序,除非 self 和 other 相等或值无法比较。
-
False:不对结果进行排序。
-
True:对结果进行排序(可能会引发 TypeError)。
返回:
索引
示例:
>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([3, 4, 5, 6])
>>> idx1.intersection(idx2)
Index([3, 4], dtype='int64')
pandas.Index.union
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.union.html
final Index.union(other, sort=None)
形成两个索引对象的并集。
如果索引对象不兼容,则首先将两个索引对象都转换为 dtype('object')。
参数:
other 索引或类数组
sort 布尔值或 None,默认为 None
是否对结果索引进行排序。
-
None:对结果进行排序,除非...
-
self 和 other 相等。
-
self 或 other 的长度为 0。
-
self 或 other 中的某些值无法进行比较。在这种情况下会发出 RuntimeWarning。
-
-
False:不对结果进行排序。
-
True:对结果进行排序(可能会引发 TypeError)。
返回:
索引
例子
合并匹配的数据类型
>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([3, 4, 5, 6])
>>> idx1.union(idx2)
Index([1, 2, 3, 4, 5, 6], dtype='int64')
合并不匹配的数据类型
>>> idx1 = pd.Index(['a', 'b', 'c', 'd'])
>>> idx2 = pd.Index([1, 2, 3, 4])
>>> idx1.union(idx2)
Index(['a', 'b', 'c', 'd', 1, 2, 3, 4], dtype='object')
多重索引情况
>>> idx1 = pd.MultiIndex.from_arrays(
... [[1, 1, 2, 2], ["Red", "Blue", "Red", "Blue"]]
... )
>>> idx1
MultiIndex([(1, 'Red'),
(1, 'Blue'),
(2, 'Red'),
(2, 'Blue')],
)
>>> idx2 = pd.MultiIndex.from_arrays(
... [[3, 3, 2, 2], ["Red", "Green", "Red", "Green"]]
... )
>>> idx2
MultiIndex([(3, 'Red'),
(3, 'Green'),
(2, 'Red'),
(2, 'Green')],
)
>>> idx1.union(idx2)
MultiIndex([(1, 'Blue'),
(1, 'Red'),
(2, 'Blue'),
(2, 'Green'),
(2, 'Red'),
(3, 'Green'),
(3, 'Red')],
)
>>> idx1.union(idx2, sort=False)
MultiIndex([(1, 'Red'),
(1, 'Blue'),
(2, 'Red'),
(2, 'Blue'),
(3, 'Red'),
(3, 'Green'),
(2, 'Green')],
)
pandas.Index.difference
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.difference.html
final Index.difference(other, sort=None)
返回一个新的 Index,其中包含不在其他对象中的元素。
这是两个 Index 对象的差集。
参数:
otherIndex 或类数组
sortbool 或 None,默认 None
是否对结果索引进行排序。默认情况下,尝试对值进行排序,但是任何无法比较的元素导致的 TypeError 都将被 pandas 捕获。
-
None:尝试对结果进行排序,但是捕获来自比较不可比较元素的任何 TypeError。
-
False:不对结果进行排序。
-
True:对结果进行排序(可能会引发 TypeError)。
返回:
Index
示例
>>> idx1 = pd.Index([2, 1, 3, 4])
>>> idx2 = pd.Index([3, 4, 5, 6])
>>> idx1.difference(idx2)
Index([1, 2], dtype='int64')
>>> idx1.difference(idx2, sort=False)
Index([2, 1], dtype='int64')
pandas.Index.symmetric_difference
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.symmetric_difference.html
Index.symmetric_difference(other, result_name=None, sort=None)
计算两个索引对象的对称差。
参数:
otherIndex 或类似数组
result_namestr
sort布尔值或 None,默认为 None
是否对结果索引进行排序。默认情况下,会尝试对值进行排序,但 pandas 会捕获任何无法比较的元素导致的 TypeError。
-
None:尝试对结果进行排序,但捕获任何由比较无法比较的元素导致的 TypeError。
-
False:不对结果进行排序。
-
True:对结果进行排序(可能会引发 TypeError)。
返回值:
索引
注意
symmetric_difference
包含出现在 idx1
或 idx2
中但不同时出现的元素。相当于 idx1.difference(idx2) | idx2.difference(idx1)
创建的索引,重复的元素将被删除。
示例
>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([2, 3, 4, 5])
>>> idx1.symmetric_difference(idx2)
Index([1, 5], dtype='int64')
pandas.Index.asof
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.asof.html
final Index.asof(label)
返回索引中的标签,如果不存在,则返回前一个标签。
假设索引已排序,如果传递的索引标签在索引中,则返回该索引标签,如果传递的索引标签不在索引中,则返回前一个索引标签。
参数:
label对象
方法返回最新索引标签直到的标签。
返回:
对象
如果标签在索引中,则为传递的标签。如果传递的标签不在排序索引中,则为前一个标签,如果没有这样的标签,则为 NaN。
另请参见
返回一个 Series 中直到传递的索引的最新值。
执行一个近似合并(类似于左连接,但它匹配最近的键而不是相等的键)。
一个 asof 是一个对 get_loc 的薄包装,方法为 'pad'。
示例
Index.asof 返回最新的索引标签直到传递的标签。
>>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03'])
>>> idx.asof('2014-01-01')
'2013-12-31'
如果标签在索引中,则该方法返回传递的标签。
>>> idx.asof('2014-01-02')
'2014-01-02'
如果索引中的所有标签都晚于传递的标签,则返回 NaN。
>>> idx.asof('1999-01-02')
nan
如果索引未排序,则会引发错误。
>>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02',
... '2014-01-03'])
>>> idx_not_sorted.asof('2013-12-31')
Traceback (most recent call last):
ValueError: index must be monotonic increasing or decreasing
pandas.Index.asof_locs
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.asof_locs.html
Index.asof_locs(where, mask)
返回索引中标签的位置(索引)。
如pandas.Index.asof()
方法中所述,如果标签(where
中的特定条目)不在索引中,则选择最近的索引标签直到传递的标签,并返回其索引。
如果索引中的所有标签都晚于where
中的标签,则返回-1。
在计算过程中,mask
用于忽略索引中的NA
值。
参数:
where索引
由时间戳数组组成的索引。
masknp.ndarray[bool]
一个布尔数组,指示原始数据中的值不是NA
的位置。
返回:
np.ndarray[np.intp]
一个由索引中的标签的位置(索引)组成的数组,这些位置对应于where
中每个元素的pandas.Index.asof()
方法的返回值。
另请参见
返回索引中的标签,如果不存在,则返回前一个标签。
示例
>>> idx = pd.date_range('2023-06-01', periods=3, freq='D')
>>> where = pd.DatetimeIndex(['2023-05-30 00:12:00', '2023-06-01 00:00:00',
... '2023-06-02 23:59:59'])
>>> mask = np.ones(3, dtype=bool)
>>> idx.asof_locs(where, mask)
array([-1, 0, 1])
我们可以使用mask
来在计算过程中忽略索引中的某些值。
>>> mask[1] = False
>>> idx.asof_locs(where, mask)
array([-1, 0, 0])
pandas.Index.get_indexer
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.get_indexer.html
final Index.get_indexer(target, method=None, limit=None, tolerance=None)
计算给定当前索引的新索引的索引器和掩码。
然后应将索引器用作 ndarray.take 的输入,以将当前数据与新索引对齐。
参数:
target索引
method,可选
-
默认:仅精确匹配。
-
pad / ffill:如果没有精确匹配,则找到前一个索引值。
-
backfill / bfill:如果没有精确匹配,则使用下一个索引值。
-
nearest:如果没有精确匹配,则使用最近的索引值。如果距离相同,则通过优先选择较大的索引值来打破。
limitint,可选
目标中连续标签的最大数量,以便进行不精确匹配。
tolerance可选
用于不精确匹配的原始标签和新标签之间的最大距离。在匹配位置的索引值必须满足方程abs(index[indexer] - target) <= tolerance
。
容差可以是标量值,对所有值应用相同的容差,也可以是类似列表的值,对每个元素应用可变容差。列表样式包括列表、元组、数组、系列,必须与索引的大小完全匹配,并且其 dtype 必须与索引的类型完全匹配。
返回:
np.ndarray[np.intp]
从 0 到 n-1 的整数,表示这些位置上的索引与相应的目标值匹配。目标中的缺失值用-1 标记。
注意事项
对于不匹配的值返回-1,更多解释请参见下面的示例。
示例
>>> index = pd.Index(['c', 'a', 'b'])
>>> index.get_indexer(['a', 'b', 'x'])
array([ 1, 2, -1])
请注意,返回值是一个由index
和x
中的位置组成的数组,其中x
被标记为-1,因为它不在index
中。
pandas.Index.get_indexer_for
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.get_indexer_for.html
final Index.get_indexer_for(target)
即使非唯一,也保证返回索引器。
这将根据情况分派给get_indexer
或get_indexer_non_unique
。
返回:
np.ndarray[np.intp]
索引列表。
示例
>>> idx = pd.Index([np.nan, 'var1', np.nan])
>>> idx.get_indexer_for([np.nan])
array([0, 2])
pandas.Index.get_indexer_non_unique
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.get_indexer_non_unique.html
Index.get_indexer_non_unique(target)
计算给定当前索引的新索引的索引器和掩码。
然后应该使用索引器作为 ndarray.take 的输入,以将当前数据与新索引对齐。
参数:
目标索引
返回:
索引器np.ndarray[np.intp]
从 0 到 n-1 的整数,指示这些位置的索引与相应的目标值匹配。目标中的缺失值由-1 标记。
缺失np.ndarray[np.intp]
未找到值的目标的索引器。这些对应于索引器数组中的-1。
示例
>>> index = pd.Index(['c', 'b', 'a', 'b', 'b'])
>>> index.get_indexer_non_unique(['b', 'b'])
(array([1, 3, 4, 1, 3, 4]), array([], dtype=int64))
在下面的例子中没有匹配的值。
>>> index = pd.Index(['c', 'b', 'a', 'b', 'b'])
>>> index.get_indexer_non_unique(['q', 'r', 't'])
(array([-1, -1, -1]), array([0, 1, 2]))
由于这个原因,返回的indexer
只包含等于-1 的整数。这表明这些位置的索引和target
值之间没有匹配。返回值中的掩码[0, 1, 2]显示了第一个、第二个和第三个元素缺失。
注意返回值是一个包含两个项的元组。在下面的例子中,第一个项是index
中的位置数组。第二个项是一个掩码,显示第一个和第三个元素缺失。
>>> index = pd.Index(['c', 'b', 'a', 'b', 'b'])
>>> index.get_indexer_non_unique(['f', 'b', 's'])
(array([-1, 1, 3, 4, -1]), array([0, 2]))
pandas.Index.get_level_values
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.get_level_values.html
Index.get_level_values(level)
返回请求级别的值的索引。
这主要用于从 MultiIndex 获取单个级别的值,但也为了兼容性而在 Index 上提供。
参数:
level int 或 str
它可以是级别的整数位置或名称。
返回:
索引
调用对象,因为索引中只有一个级别。
另请参阅
获取多级索引的级别的值。
注意事项
对于索引,级别应该是 0,因为没有多个级别。
示例
>>> idx = pd.Index(list('abc'))
>>> idx
Index(['a', 'b', 'c'], dtype='object')
通过提供整数作为级别来获取级别值:
>>> idx.get_level_values(0)
Index(['a', 'b', 'c'], dtype='object')
pandas.Index.get_loc
pandas.pydata.org/docs/reference/api/pandas.Index.get_loc.html
Index.get_loc(key)
获取所请求标签的整数位置、切片或布尔掩码。
参数:
key标签
返回:
int 表示唯一索引,slice 表示单调索引,否则表示掩码。
示例
>>> unique_index = pd.Index(list('abc'))
>>> unique_index.get_loc('b')
1
>>> monotonic_index = pd.Index(list('abbc'))
>>> monotonic_index.get_loc('b')
slice(1, 3, None)
>>> non_monotonic_index = pd.Index(list('abcb'))
>>> non_monotonic_index.get_loc('b')
array([False, True, False, True])
pandas.Index.get_slice_bound
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.get_slice_bound.html
Index.get_slice_bound(label, side)
计算与给定标签对应的切片边界。
返回给定标签的最左边位置(如果side=='right'
,则为最右边的位置)。
参数:
label对象
side
返回:
int
标签的索引。
另请参阅
Index.get_loc
获取请求标签的整数位置、切片或布尔掩码。
示例
>>> idx = pd.RangeIndex(5)
>>> idx.get_slice_bound(3, 'left')
3
>>> idx.get_slice_bound(3, 'right')
4
如果索引中的label
不唯一,则会引发错误。
>>> idx_duplicate = pd.Index(['a', 'b', 'a', 'c', 'd'])
>>> idx_duplicate.get_slice_bound('a', 'left')
Traceback (most recent call last):
KeyError: Cannot get left slice bound for non-unique label: 'a'
pandas.Index.isin
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.isin.html
Index.isin(values, level=None)
返回一个布尔数组,其中索引值在 values 中。
计算布尔数组,指示每个索引值是否在传递的值集中找到。返回的布尔数组的长度与索引的长度相匹配。
参数:
values集合或类似列表
所寻找的值。
level字符串或整数,可选
要使用的索引级别的名称或位置(如果索引是 MultiIndex)。
返回:
np.ndarray[bool]
布尔值的 NumPy 数组。
另请参阅
对于 Series 也是一样的。
DataFrames 的相同方法。
注意事项
对于 MultiIndex 情况,您必须将值指定为包含元组的类似列表对象,该元组的长度与级别数相同,或者指定级别。否则,它将引发ValueError
。
如果指定了级别:
-
如果它是一个且仅一个索引级别的名称,请使用该级别;
-
否则,它应该是一个指示级别位置的数字。
示例
>>> idx = pd.Index([1,2,3])
>>> idx
Index([1, 2, 3], dtype='int64')
检查值列表中的每个索引值。
>>> idx.isin([1, 4])
array([ True, False, False])
>>> midx = pd.MultiIndex.from_arrays([[1,2,3],
... ['red', 'blue', 'green']],
... names=('number', 'color'))
>>> midx
MultiIndex([(1, 'red'),
(2, 'blue'),
(3, 'green')],
names=['number', 'color'])
检查 MultiIndex 的“color”级别中的字符串是否在颜色列表中。
>>> midx.isin(['red', 'orange', 'yellow'], level='color')
array([ True, False, False])
要跨多个索引级别检查,请传递一个元组列表:
>>> midx.isin([(1, 'red'), (3, 'red')])
array([ True, False, False])
pandas.Index.slice_indexer
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.slice_indexer.html
Index.slice_indexer(start=None, end=None, step=None)
计算输入标签和步数的切片索引器。
索引需要被排序并且唯一。
参数:
start标签,默认为 None
如果为 None,默认为开始。
end标签,默认为 None
如果为 None,默认为结束。
step整数,默认为 None
返回:
切片
引发:
KeyError如果键不存在,或键不唯一且索引不唯一
未排序。
注释
此函数假定数据已经排序,所以使用需谨慎
示例
这是所有索引类型的方法。例如你可以这样做:
>>> idx = pd.Index(list('abcd'))
>>> idx.slice_indexer(start='b', end='c')
slice(1, 3, None)
>>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])
>>> idx.slice_indexer(start='b', end=('c', 'g'))
slice(1, 3, None)
pandas.Index.slice_locs
原文:
pandas.pydata.org/docs/reference/api/pandas.Index.slice_locs.html
Index.slice_locs(start=None, end=None, step=None)
计算输入标签的切片位置。
参数:
start标签,默认为 None
如果为 None,则默认为开始位置。
end标签,默认为 None
如果为 None,则默认为末尾。
step整数,默认为 None
如果为 None,则默认为 1。
返回:
元组[整数, 整数]
另请参阅
获取单个标签的位置。
注意事项
此方法仅在索引单调或唯一时有效。
示例
>>> idx = pd.Index(list('abcd'))
>>> idx.slice_locs(start='b', end='c')
(1, 3)
pandas.RangeIndex
原文:
pandas.pydata.org/docs/reference/api/pandas.RangeIndex.html
class pandas.RangeIndex(start=None, stop=None, step=None, dtype=None, copy=False, name=None)
实现单调整数范围的不可变索引。
RangeIndex 是一种节省内存的特殊情况,限制为使用 64 位 dtype 表示单调范围。在某些情况下使用 RangeIndex 可能会提高计算速度。
当用户未提供显式索引时,此为 DataFrame 和 Series 使用的默认索引类型。
参数:
startint(默认值:0)、range 或其他 RangeIndex 实例
如果为 int 并且未提供“stop”,则解释为“stop”。
stopint(默认值:0)
stepint(默认值:1)
dtypenp.int64
未使用,仅为与其他索引类型保持一致而接受。
copybool,默认为 False
未使用,仅为与其他索引类型保持一致而接受。
nameobject,可选
要存储在索引中的名称。
另请参阅
Index
基本 pandas Index 类型。
示例
>>> list(pd.RangeIndex(5))
[0, 1, 2, 3, 4]
>>> list(pd.RangeIndex(-2, 4))
[-2, -1, 0, 1, 2, 3]
>>> list(pd.RangeIndex(0, 10, 2))
[0, 2, 4, 6, 8]
>>> list(pd.RangeIndex(2, -10, -3))
[2, -1, -4, -7]
>>> list(pd.RangeIndex(0))
[]
>>> list(pd.RangeIndex(1, 0))
[]
属性
start |
起始参数的值(如果未提供,则为 0 )。 |
---|---|
stop |
stop 参数的值。 |
step |
步长参数的值(如果未提供,则为 1 )。 |
方法
from_range (data[, name, dtype]) |
从 range 对象创建 pandas.RangeIndex 。 |
---|
pandas.RangeIndex.start
原文:
pandas.pydata.org/docs/reference/api/pandas.RangeIndex.start.html
property RangeIndex.start
起始参数的值(如果未提供则为0
)。
示例
>>> idx = pd.RangeIndex(5)
>>> idx.start
0
>>> idx = pd.RangeIndex(2, -10, -3)
>>> idx.start
2
pandas.RangeIndex.stop
原文:
pandas.pydata.org/docs/reference/api/pandas.RangeIndex.stop.html
property RangeIndex.stop
停止参数的值。
例子
>>> idx = pd.RangeIndex(5)
>>> idx.stop
5
>>> idx = pd.RangeIndex(2, -10, -3)
>>> idx.stop
-10
pandas.RangeIndex.step
原文:
pandas.pydata.org/docs/reference/api/pandas.RangeIndex.step.html
property RangeIndex.step
步长参数的值(如果未提供,则为 1
)。
示例
>>> idx = pd.RangeIndex(5)
>>> idx.step
1
>>> idx = pd.RangeIndex(2, -10, -3)
>>> idx.step
-3
即使 pandas.RangeIndex
为空,如果未提供,则 step
仍然为 1
。
>>> idx = pd.RangeIndex(1, 0)
>>> idx.step
1
pandas.RangeIndex.from_range
原文:
pandas.pydata.org/docs/reference/api/pandas.RangeIndex.from_range.html
classmethod RangeIndex.from_range(data, name=None, dtype=None)
从range
对象中创建pandas.RangeIndex
。
返回:
RangeIndex
示例
>>> pd.RangeIndex.from_range(range(5))
RangeIndex(start=0, stop=5, step=1)
>>> pd.RangeIndex.from_range(range(2, -10, -3))
RangeIndex(start=2, stop=-10, step=-3)
pandas.CategoricalIndex
原文:
pandas.pydata.org/docs/reference/api/pandas.CategoricalIndex.html
class pandas.CategoricalIndex(data=None, categories=None, ordered=None, dtype=None, copy=False, name=None)
基于底层的 Categorical
的索引。
CategoricalIndex,如同 Categorical,只能取有限的,通常是固定的可能值(类别)。也像 Categorical 一样,它可能有一个顺序,但是不可能进行数值运算(加法、除法等)。
参数:
dataarray-like(1-dimensional)
分类的值。如果给定了类别,则不在类别中的值将被替换为 NaN。
categoriesindex-like,可选
分类的类别。项目需要是唯一的。如果这里没有给出类别(也不在 dtype 中),它们将从数据中推断出来。
orderedbool,可选
此分类是否被视为有序分类。如果未在此处或 dtype 中给出,则结果分类将是无序的。
dtypeCategoricalDtype 或 “category”,可选
如果CategoricalDtype
,不能与类别或 ordered 一起使用。
copybool,默认为 False
复制输入的 ndarray。
nameobject,可选
要存储在索引中的名称。
Raises:
ValueError
如果类别不被验证。
TypeError
如果给定了显式的ordered=True
但没有类别,并且值不可排序。
另请参见
Index
pandas 的基本索引类型。
Categorical
一个分类数组。
CategoricalDtype
用于分类数据的类型。
注意
更多信息请参阅用户指南。
示例
>>> pd.CategoricalIndex(["a", "b", "c", "a", "b", "c"])
CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'],
categories=['a', 'b', 'c'], ordered=False, dtype='category')
CategoricalIndex
也可以从 Categorical
实例化:
>>> c = pd.Categorical(["a", "b", "c", "a", "b", "c"])
>>> pd.CategoricalIndex(c)
CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'],
categories=['a', 'b', 'c'], ordered=False, dtype='category')
有序的 CategoricalIndex
可以有最小值和最大值。
>>> ci = pd.CategoricalIndex(
... ["a", "b", "c", "a", "b", "c"], ordered=True, categories=["c", "b", "a"]
... )
>>> ci
CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'],
categories=['c', 'b', 'a'], ordered=True, dtype='category')
>>> ci.min()
'c'
属性
codes |
此分类索引的类别代码。 |
---|---|
categories |
这个分类的类别。 |
ordered |
类别是否有顺序关系。 |
方法
rename_categories (*args, **kwargs) |
重命名类别。 |
---|---|
reorder_categories (*args, **kwargs) |
按照新类别重新排序类别。 |
add_categories (*args, **kwargs) |
添加新的类别。 |
remove_categories (*args, **kwargs) |
删除指定的类别。 |
remove_unused_categories (*args, **kwargs) |
删除未使用的类别。 |
set_categories (*args, **kwargs) |
将类别设置为指定的新类别。 |
as_ordered (*args, **kwargs) |
将分类设置为有序。 |
as_unordered (*args, **kwargs) |
将分类设置为无序。 |
map (mapper[, na_action]) |
使用输入的映射或函数对值进行映射。 |
pandas.CategoricalIndex.codes
原文:
pandas.pydata.org/docs/reference/api/pandas.CategoricalIndex.codes.html
property CategoricalIndex.codes
此分类索引的类别代码。
代码是整数数组,是实际值在类别数组中的位置。
没有设置器,请使用其他分类方法和正常的项设置器更改分类中的值。
返回:
ndarray[int]
codes
数组的不可写视图。
示例
对于 pandas.Categorical
:
>>> cat = pd.Categorical(['a', 'b'], ordered=True)
>>> cat.codes
array([0, 1], dtype=int8)
对于 pandas.CategoricalIndex
:
>>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'])
>>> ci.codes
array([0, 1, 2, 0, 1, 2], dtype=int8)
>>> ci = pd.CategoricalIndex(['a', 'c'], categories=['c', 'b', 'a'])
>>> ci.codes
array([2, 0], dtype=int8)
pandas.CategoricalIndex.categories
原文:
pandas.pydata.org/docs/reference/api/pandas.CategoricalIndex.categories.html
property CategoricalIndex.categories
此分类的类别。
设置为每个类别分配新值(实际上是对每个单独类别进行重命名)。
分配的值必须是类似列表的对象。所有项目必须是唯一的,并且新类别中的项目数量必须与旧类别中的项目数量相同。
引发:
ValueError
如果新类别无法验证为类别,或者新类别的数量与旧类别的数量不相等
另请参阅
rename_categories
重命名类别。
reorder_categories
重新排序类别。
add_categories
添加新类别。
remove_categories
删除指定的类别。
remove_unused_categories
删除未使用的类别。
set_categories
将类别设置为指定的类别。
示例
对于pandas.Series
:
>>> ser = pd.Series(['a', 'b', 'c', 'a'], dtype='category')
>>> ser.cat.categories
Index(['a', 'b', 'c'], dtype='object')
>>> raw_cat = pd.Categorical(['a', 'b', 'c', 'a'], categories=['b', 'c', 'd'])
>>> ser = pd.Series(raw_cat)
>>> ser.cat.categories
Index(['b', 'c', 'd'], dtype='object')
对于pandas.Categorical
:
>>> cat = pd.Categorical(['a', 'b'], ordered=True)
>>> cat.categories
Index(['a', 'b'], dtype='object')
对于pandas.CategoricalIndex
:
>>> ci = pd.CategoricalIndex(['a', 'c', 'b', 'a', 'c', 'b'])
>>> ci.categories
Index(['a', 'b', 'c'], dtype='object')
>>> ci = pd.CategoricalIndex(['a', 'c'], categories=['c', 'b', 'a'])
>>> ci.categories
Index(['c', 'b', 'a'], dtype='object')