【发布时间】:2021-07-06 15:23:33
【问题描述】:
我正在使用 Pandas 处理一些温度数据。
感谢这行代码,我从一个名为“data”的 DataFrame 获得了第一个数据观察结果:
first_obs = data['DATE'][0]
请记住,data['DATE'] 是 pandas.Series 对象。 数据索引:STATION ELEVATION LATITUDE LONGITUDE DATE PRCP TAVG TMAX TMIN YEAR MONTH
经过一些数据处理后,我创建了一个新的 DataFrame 'monthly_data',其中包含以下索引:MONTH TAVG YEAR temp_celsius ref_temp diff abs_diff
现在我想在 'abs_diff' 列中获取该数据帧中具有最大值的行:
weather_anomaly = monthly_data.loc[monthly_data['abs_diff'] == monthly_data['abs_diff'].max()]
现在 weather_anomaly 是另一个 DataFrame 对象,所以现在出现了奇怪的问题: 如果我像以前这样写代码:
weather_anomaly['MONTH'][0]
出现错误:
KeyError Traceback(最近调用 最后的) ~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py 在 get_loc(self, key, method, tolerance) 3079 中尝试: -> 3080 return self._engine.get_loc(casted_key) 3081 除了 KeyError as err:
pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.Int64HashTable.get_item()
pandas_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.Int64HashTable.get_item()
密钥错误:0
上述异常是以下异常的直接原因:
KeyError Traceback(最近调用 最后)在 ----> 1 weather_anomaly['MONTH'][0] 2 print('温度异常最大的月份是', weather_anomaly['MONTH'].values[0], 'of the year', weather_anomaly['YEAR'].values[0], ' 相差 ', weather_anomaly['diff'].values[0])
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py 在getitem(自我,钥匙) 851 第852章 --> 853 返回 self._get_value(key) 854 第855章
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable) 959 960 # 类似于 Index.get_value,但我们不回退到位置 --> 961 loc = self.index.get_loc(label) 第962章 963
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py 在 get_loc(self、key、method、tolerance) 3080
返回 self._engine.get_loc(casted_key) 3081 除外 KeyError 错误: -> 3082 raise KeyError(key) from err 3083 3084 if tolerance不是None:密钥错误:0
没有任何解释出现。 幸运的是,这个问题的解决方案很简单:
weather_anomaly['MONTH'].values[0]
所以最后一个问题是尽管 data['DATE'] 和monthly_data['abs_diff'] 都是熊猫。Series 对象为什么 weather_anomaly['abs_diff'][0] 不起作用?
【问题讨论】:
标签: python pandas series getvalue