【问题标题】:Pandas: KeyError when using column names which are included in an indexPandas:使用包含在索引中的列名时出现 KeyError
【发布时间】:2017-08-24 23:28:50
【问题描述】:

我有我正在解析的文本文件,其中包含固定宽度的字段,其行如下所示:

USC00142401201703TMAX  211  H  133  H  161  H  194  H  206  H  161  H  244  H  178  H-9999     250  H   78  H   44  H   67  H   50  H   39  H  106  H  239  H  239  H  217  H  317  H  311  H  178  H  139  H-9999     228  H-9999   -9999   -9999   -9999   -9999   -9999   

我正在将它们解析为 pandas DataFrame,如下所示:

from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np

def read_into_dataframe(station_filepath):

    # specify the fixed-width fields
    column_specs = [(0, 11),   # ID
                    (11, 15),  # year
                    (15, 17),  # month
                    (17, 21),  # variable (referred to as element in the GHCND readme.txt)
                    (21, 26),  # day 1
                    (29, 34),  # day 2
                    (37, 42),  # day 3
                    (45, 50),  # day 4
                    (53, 58),  # day 5
                    (61, 66),  # day 6
                    (69, 74),  # day 7
                    (77, 82),  # day 8
                    (85, 90),  # day 9
                    (93, 98),  # day 10
                    (101, 106),  # day 11
                    (109, 114),  # day 12
                    (117, 122),  # day 13
                    (125, 130),  # day 14
                    (133, 138),  # day 15
                    (141, 146),  # day 16
                    (149, 154),  # day 17
                    (157, 162),  # day 18
                    (165, 170),  # day 19
                    (173, 178),  # day 20
                    (181, 186),  # day 21
                    (189, 194),  # day 22
                    (197, 202),  # day 23
                    (205, 210),  # day 24
                    (213, 218),  # day 25
                    (221, 226),  # day 26
                    (229, 234),  # day 27
                    (237, 242),  # day 28
                    (245, 250),  # day 29
                    (253, 258),  # day 30
                    (261, 266)]  # day 31

    # create column names to correspond with the fields specified above
    column_names = ['station_id', 'year', 'month', 'variable',
                    '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',  
                    '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',  
                    '21', '22', '23', '24', '25', '26', '27', '28', '29', '30',  '31']

    # read the fixed width file into a DataFrame columns with the widths and names specified above
    df = pd.read_fwf(station_filepath, 
                     header=None,
                     colspecs=column_specs,
                     names=column_names,
                     na_values=-9999)

    # convert the variable column to string data type, all others as integer data type
    df.dropna()  #REVISIT do we really want to do this?
    df['variable'] = df['variable'].astype(str)

    # keep only the rows where the variable value is 'PRCP', 'TMIN', or 'TMAX'
    df = df[df['variable'].isin(['PRCP', 'TMAX', 'TMIN'])]

    # melt the individual day columns into a single day column
    df = pd.melt(df,
                 id_vars=['station_id', 'year', 'month', 'variable'],
                 value_vars=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                             '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
                             '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
                 var_name='day', 
                 value_name='value')

    # pivot the DataFrame on the variable type (PRCP, TMIN, TMAX), so each
    # type has a separate column with the day's value for the type
    df = df.pivot_table(index=['year',
                               'month',
                               'day'],
                        columns='variable',
                        values='value')

    return df

我现在得到了我想要的形状的 DataFrame,除了有一些不存在的日期(即 2 月 31 日等)的行,我想删除这些行。

我尝试使用掩码来执行此操作,但是当我这样做时,当我尝试使用我认为是有效的列名时会收到 KeyError。例如,如果我在返回 DataFrame 之前在上述函数中包含以下代码,我将得到一个 KeyError:

months_with_31days = [1, 3, 7, 8, 10, 12]
df = df[((df['day'] == 31) & (df['month'] in months_with_31days))
        |
       ((df['day'] == 30) & (df['month'] != 2))
        |
       ((df['day'] == 29) & (df['month'] != 2))
        |
       ((df['day'] == 29) & (df['month'] == 2) & calendar.isleap(df['year']))
        | 
        df['day'] < 29]

以上将导致KeyError:

KeyError: 'day'

day 变量由melt() 调用创建,然后在调用pivot_table() 的索引中使用。这如何影响 DataFrame 的索引以及为什么它会阻碍使用先前列名的能力,我不清楚。 [编辑]我假设我现在在 DatFrame 上有一个 MultiIndex,它是通过使用索引参数调用 pivot_table() 而创建的。

打印DataFrame时显示的初始行:

variable         PRCP   TMAX   TMIN
year month day                     
1893 1     01     NaN   61.0   33.0
           02     NaN   33.0    6.0
           03     NaN   44.0   17.0
           04     NaN   78.0   22.0
           05     NaN   17.0  -94.0
           06     NaN   33.0    0.0
           07     NaN    0.0  -67.0

我尝试使用点表示法而不是带引号的列名的括号来引用 DataFrame 的列,但我得到了类似的错误。似乎年、月和日列已合并为单个索引列,不能再单独引用。或者不是,也许这里发生了其他事情?我很难过,也许甚至没有以最好的方式解决这个问题,任何帮助或建议将不胜感激。谢谢。

【问题讨论】:

  • 你可以通过your_df_name.columns.values找到列名。你的专栏有哪些?
  • 感谢这个想法。 DataFrame 列值:['PRCP' 'TMAX' 'TMIN'] DataFrame 索引名称:['year', 'month', 'day']。好像我已经将年、月和日的列/标签移到了索引中。这不是我的实际意图,我真的想要一个正常的索引以及实际的年、月和日列,这对于进一步缩减数据很有用,就像删除代表不存在的日期的行一样。我尝试以各种不同的方式调用上面的 pivot_table() 和 melt() 函数,但没有任何效果。
  • 你能显示最终df的标题吗?它可能是多索引的,这意味着你不能做 df['day']
  • 我认为你是对的,我现在可能有一个 MultiIndex。我现在不在工作,所以还不能显示标题,但它看起来确实与我见过的许多 MultiIndex 示例相似,所以很可能是这种情况。所以我现在有一个 MultiIndex,其中顶层是年,下一个是月,最后一个是天。 ...
  • ... 我的假设是 DataFrame 中的每一行都有年、月和日值,但现在这些不是正确的列(而是 MultiIndex 中的字段),因此可以' 不使用括号表示法来引用。如果这是真的,那么引用这些值的正确表示法是什么,以便我可以使用它们来过滤掉无效/不存在日期的行?

标签: python pandas dataframe


【解决方案1】:

是的,您已经创建了一个多索引 DataFrame。通过查看您的输出(无需访问您的数据),您应该能够通过键入以下内容来访问日期:

df['variable']['day']

【讨论】:

    猜你喜欢
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2019-08-16
    • 2013-03-13
    • 2016-11-22
    • 2018-04-30
    相关资源
    最近更新 更多