从 Pandas 系列中获取价值

Get value from Pandas Series

我正在使用 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 差异 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 (most recent call last) ~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 3079 try: -> 3080 return self._engine.get_loc(casted_key) 3081 except 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 in pandas._libs.hashtable.Int64HashTable.get_item()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError Traceback (most recent call last) in ----> 1 weather_anomaly['MONTH'][0] 2 print('The month with the greatest temperature anomaly is ', weather_anomaly['MONTH'].values[0], 'of the year ', weather_anomaly['YEAR'].values[0], ' with a difference of ', weather_anomaly['diff'].values[0])

~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py in getitem(self, key) 851 852 elif key_is_scalar: --> 853 return self._get_value(key) 854 855 if is_hashable(key):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable) 959 960 # Similar to Index.get_value, but we do not fall back to positional --> 961 loc = self.index.get_loc(label) 962 return self.index._get_values_for_loc(self, loc, label) 963

~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 3080
return self._engine.get_loc(casted_key) 3081 except KeyError as err: -> 3082 raise KeyError(key) from err 3083 3084 if tolerance is not None:

KeyError: 0

没有解释。 幸运的是这个问题的解决方案很简单:

weather_anomaly['MONTH'].values[0]

所以最后的问题是尽管数据['DATE']和monthly_data['abs_diff']都是pandas.系列 对象为什么 weather_anomaly['abs_diff'][0] 不起作用?

TL;DR 原因是 weather_anomaly['MONTH'] 的索引不是正常整数。

After some data manipulation i created a new DataFrame monthly_data with these indexes: MONTH TAVG YEAR temp_celsius ref_temp diff abs_diff

weather_anomaly = monthly_data.loc[monthly_data['abs_diff'] == monthly_data['abs_diff'].max()]

正如你上面所说, monthly_data 的索引不是整数。对 monthly_data 进行操作后得到 weather_anomalyweather_anomaly 的索引就像 monthly_data.

如果要按整数定位Series,可以使用pandas.Series.iloc()。在你的例子中,

weather_anomaly['MONTH'].iloc[0]

我假设您的原始 DataFrame 有一个带有递增整数的索引列,因此在您的第一个示例中,data['DATE'][0]data['DATE'].iloc[0] return 结果相同。

但是在 select 具有 max() 条件的特定行之后,新的 DataFrame weather_anomaly 仅包含一行 保留其原始索引 不能为零。

因此,为了select第一行weather_anomaly,您需要使用.iloc[0]reset_index()并使用[0]

我建议你打印你的数据帧,你会清楚地看到索引列的行为。