为什么.loc在Python Pandas系列中不起作用?

问题描述 投票:0回答:1

我用过滤器得到所需的日期'2013-09-12'的行。是不是因为标签'date'是一个indecies的标签,而indecies是'2013-09-12'日期。其中'.loc',我相信,是看列和行标签值。我的理解是否正确?

mean_altitudes_perday = grouped_bydates.altitude.mean()

print(mean_altitudes_perday)
print(mean_altitudes_perday.loc[mean_altitudes_perday['date']] == '2013-09-12') # Why loc is not working here?


# Q: What is the mean altitude of the birds on 2013-09-12?
# A: print(mean_altitudes_perday.filter(like='2013-09-12', axis=0))

错误信息。

date
2013-08-15    134.092000
2013-08-16    134.839506
2013-08-17    147.439024
2013-08-18    129.608163
2013-08-19    180.174797
                 ...    
2014-04-26     15.118012
2014-04-27     23.897297
2014-04-28     37.716867
2014-04-29     19.244792
2014-04-30     13.954545
Name: altitude, Length: 259, dtype: float64
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   4410             try:
-> 4411                 return libindex.get_value_at(s, key)
   4412             except IndexError:

# Had to delete a lot of error code due to posting requirements

KeyError: 'date'
pandas series
1个回答
1
投票

它看起来像 每日平均海拔高度 是一个 系列,索引名为 日期.

可能包含一些DataFrame 日期海拔 列,您创建了 每日平均海拔高度 执行类似的东西。

mean_altitudes_perday = df.set_index('date').altitude

Name: altitude 如果你的打印输出的最后一行。名称系列继承自原始column名称,索引也是继承自原始名称。

当你执行类似 mean_altitudes_perday['date'],熊猫 试图寻找 '日期' (一个字符串)的索引中,并返回这个 系列.

由于该索引没有元素==。'日期'异常(按键错误)被提出。

也许这个异常更有意义的名字应该是 索引错误(索引中没有对应的值),但我们对此无能为力。

但是如果你执行例如 mean_altitudes_perday['2013-08-19']的时候,你会得到一个值 (180.174797).

您也可以运行 mean_altitudes_perday.loc['2013-08-19'] (一般来说,通过任何 现有 索引值),结果相同。

© www.soinside.com 2019 - 2024. All rights reserved.