pandas中关于倒序索引【如df[-1]或series[-1]】的用法总结【有一个很大的坑】

论坛 期权论坛 脚本     
匿名技术用户   2021-1-14 14:39   688   0

遇到的问题:关于df_a_series[-1]为什么要是时间序列索引才能访问,而非时间序列索引,直接报错:

 File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 88, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 992, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 998, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: -1

测试案例【万能用法:df_a_series.iloc[-1]】:

import pandas as pd

se = pd.Series([1, 2, 3, 4])
index = pd.date_range("2019-09-01", "2019-09-02")

df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
# print(df)

# 关于Series实例的倒序索引玩法总结
df_a_series = df["a"]

print(df_a_series[-1])  # 直接报错【这种用法经常碰到,测试发现,如果index为时间索引,则可以,否则失败】

print(df_a_series.iloc[-1])  # 这个肯定是成功的【这个是万能的玩法】

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP