来自 R 背景的我发现Indexpandas 中对象的(非常高)使用有点令人不安。例如,如果train是 pandas DataFrame,是否有一些特殊原因train.columns应该返回Index而不是列表?如果它是一个物体,还会有什么目的Index?根据 的定义pandas.Index,它是所有 pandas 对象存储轴标签的基本对象。虽然train.index.values返回行标签(axis=0),但如何从中获取列标签或列名称pandas.index?与之前的问题不同,在这个问题中,我想到了一个具体的例子。
Apd.Index是列名的类似数组的容器,因此在某种意义上,询问如何从索引获取标签是没有意义的,因为索引就是标签。
也就是说,您始终可以使用 获取底层 numpy 数组df.columns.values,或者使用 @Mitch 所示转换为 python 列表tolist()。
就为什么在裸数组上使用索引而言 -Index提供了整个 pandas 中使用的额外功能/性能 - 其核心是基于哈希表的索引。
例如,考虑以下框架/列。
df = pd.DataFrame(np.random.randn(10, 10),
columns=list('abcdefghkm'))
cols = df.columns
cols
Out[16]: Index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'm'], dtype='object')
Run Code Online (Sandbox Code Playgroud)
现在假设您要从'h'框架中选择列。对于列的列表或数组版本,您可以循环遍历列以查找 的位置'h',该位置O(n)在列数中 - 如下所示:
for i, col in enumerate(cols):
if col == 'h':
found_loc = i
break
found_loc
Out[18]: 7
df.values[:, found_loc]
Out[19]:
array([-0.62916208, 2.04403495, 0.29498066, 1.07939374, -1.49619915,
-0.54592646, -1.04382192, -0.45934113, -1.02935858, 1.62439231])
df['h']
Out[20]:
0 -0.629162
1 2.044035
2 0.294981
3 1.079394
4 -1.496199
5 -0.545926
6 -1.043822
7 -0.459341
8 -1.029359
9 1.624392
Name: h, dtype: float64
Run Code Online (Sandbox Code Playgroud)
使用Index,pandas 构建了列值的哈希表,因此查找“h”的位置是一个摊销O(1)操作,通常要快得多,特别是在列数很大的情况下。
df.columns.get_loc('h')
Out[21]: 7
Run Code Online (Sandbox Code Playgroud)
此示例仅选择单个列,但正如 @ayhan 在评论中指出的那样,相同的哈希表结构还加速了许多其他操作,如合并、对齐、过滤和分组。
| 归档时间: |
|
| 查看次数: |
7917 次 |
| 最近记录: |