Pandas的索引index的用途

Pandas index的用途:

  1. 更方便的数据查询
  2. 使用Index可以获得性能提升
  3. 自动的数据对齐功能
  4. 更多更强大的数据结构支持
0. 读取数据

import pandas as pd
file_path = r'C:\TELCEL_MEXICO_BOT\A\Movie.csv'
df = pd.read_csv(file_path,encoding='utf-8')
print(df.head()) ## 查看前5行数据
   userId  movieId  rating  timestamp
0      10      104       6        255
1      12      120       7        294
2      13      136       4        333
3      15      152       7        372
4      16      168       5        411
print(df.count())  ## 查看数据有多少条
userId       39
movieId      39
rating       39
timestamp    39
dtype: int64

1. 使用index查询数据

## drop==False,让索引列还保持在column

注意,数据体的内容是中间那块

df.set_index('userId',inplace=True,drop=False)
print(df.head())
        userId  movieId  rating  timestamp
userId                                    
10          10      104       6        255
12          12      120       7        294
13          13      136       4        333
15          15      152       7        372
16          16      168       5        411
print(df.index)
Int64Index([10, 12, 13, 15, 16, 18, 20, 24, 27, 30, 33, 36, 40, 43, 46, 49, 52,
            56, 59, 62, 65, 68, 72, 75, 78, 81, 84, 88, 91, 94, 97, 10, 11, 14,
            16, 19, 25, 35, 40],
           dtype='int64', name='userId')
print(df.loc[78]) ##使用index进行查询
        userId  movieId  rating  timestamp
userId                                    
78          78      784       7       1917
78          78     1008      10       2465

2. 使用column的condition查询方法

print(df.loc[df['userId'] == 78].head())
        userId  movieId  rating  timestamp
userId                                    
78          78      784       7       1917
78          78     1008      10       2465

3. 使用index会提升查询性能

查询代码时间

code_to_test = "df.loc[78]"
# 运行 timeit 并获取结果
execution_time = timeit.timeit(code_to_test, globals=globals(), number=1000)  # number 是执行次数
Execution time: 0.000039 seconds per loop
  • 在查询数据时,建议先把要查询的数据排序,然后再查询,这样可以节省数据查询时间

4. 使用index更多更强大的数据结构支持

CategoricallIndex, 基于分类数据的Index,提升性能

MultiIndex, 多维索引,用于groupby多维聚合后的结果

DatatimeIndex, 时间类型索引,强大的日期和日间的方法支持

### 如何使用 Pandas 库中的 `reset_index` 方法重置 DataFrame 的行索引 Pandas 提供了一种简单有效的方式来重置 DataFrame 的行索引,即通过调用 `reset_index()` 方法。该方法的主要功能是将当前的索引替换为默认的整数索引,并可以选择是否保留原始索引作为新列的一部分[^1]。 以下是关于 `reset_index` 方法的一些重要特性: - **基本用途**:当需要重新定义数据帧的索引结构时,可以利用 `reset_index` 将其转换成基于连续整数值的新索引体系[^2]。 - **参数说明**: - 如果设置了 `drop=True` 参数,则不会保存旧有的索引到新的列中;反之,默认情况下会创建一列存储原来的索引值[^4]。 - 当存在多级索引(MultiIndex)的情况下,可以通过指定额外选项控制哪些级别的层次被移除或者调整[^3]。 #### 示例代码展示 下面给出一段具体的 Python 实现示例来演示这一过程: ```python import pandas as pd data = {'A': [1, 2, 1], 'B': [5, 1, 1], 'C': [2, 8, 4]} df = pd.DataFrame(data) # 假设此时索引已经被打乱 df.index = [7, 9, 1] print("初始状态下的 DataFrame:") print(df) # 调用 reset_index 并丢弃原有索引 new_df = df.reset_index(drop=True) print("\n重置索引后的 DataFrame (不保留原索引):") print(new_df) # 或者可以在原地修改而不返回副本 df.reset_index(drop=True, inplace=True) print("\n在原 DataFrame 上应用更改的结果:") print(df) ``` 上述脚本展示了两种不同的方式来进行索引重建操作——既可以生成一份带有更新后布局的数据集拷贝,也可以直接作用于源对象之上完成同样的任务[^5]。 ### 注意事项 需要注意的是,在某些场景下可能还需要考虑其他因素比如性能影响以及对于大型表格的操作效率等问题。因此实际开发过程中应根据具体需求合理选用相应策略。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值