【问题标题】:Index pandas data frame by index按索引索引 pandas 数据帧
【发布时间】:2019-08-23 23:19:48
【问题描述】:

示例数据框:

data = [["2011-01-01",23],["2011-01-02",33],["2011-01-03",43],["2011-01-04",53]]
df= pd.DataFrame(data,columns = ["A","B"])
df["A"] = pd.to_datetime(df["A"])
df.index = df["A"]
del df["A"]

操作:

            B
A   
2011-01-01  23
2011-01-02  33
2011-01-03  43
2011-01-04  53

我正在尝试使用以下代码将此数据框拆分为两部分:

part1 = df.loc[:"2011-01-02"]

操作:

            B
A   
2011-01-01  23
2011-01-02  33

第二部分:

part2 = df.loc["2011-01-02":]

操作:

            B
A   
2011-01-02  33
2011-01-03  43
2011-01-04  53

但是索引为“2011-01-02”的行在两个部分(part1 和 part2)中。对 pandas 1-liners 的任何建议,以仅在 1 部分而不是两者中获得该行。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这种行为是预期的(直到今天我也不知道)

    这种类型的切片适用于具有 DatetimeIndex 的 DataFrame 出色地。由于部分字符串选择是标签切片的一种形式, 端点将被包括在内。这将包括匹配时间 包含日期: 来自http://pandas-docs.github.io/pandas-docs-travis/user_guide/timeseries.html#indexing

    关于标签切片行为

    请注意,与通常的 python 切片相反,开始和停止都包括在内 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html#pandas.DataFrame.loc

    In [16]: df[df.index < '2011-01-02']
    Out[16]:
                 B
    A
    2011-01-01  23
    
    In [17]: df[df.index >= '2011-01-02']
    Out[17]:
                 B
    A
    2011-01-02  33
    2011-01-03  43
    2011-01-04  53
    
    In [18]: df[df.index > '2011-01-02']
    Out[18]:
                 B
    A
    2011-01-03  43
    2011-01-04  53
    

    【讨论】:

      【解决方案2】:
      slice = df.index > "2011-01-02"
      df[slice]
      df[~slice]
      

      【讨论】:

        【解决方案3】:

        get_lociloc 一起使用

        df.iloc[:df.index.get_loc('2011-01-02')]
                            A   B
        A                        
        2011-01-01 2011-01-01  23
        
        df.iloc[df.index.get_loc('2011-01-02'):]
                            A   B
        A                        
        2011-01-02 2011-01-02  33
        2011-01-03 2011-01-03  43
        2011-01-04 2011-01-04  53
        

        【讨论】:

          【解决方案4】:

          而不是part2 = df.loc["2011-01-02":] 使用

          part2 = df.loc["2011-01-02":].iloc[1:]
          
                       B
          A             
          2011-01-03  43
          2011-01-04  53
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-07-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-12
            • 1970-01-01
            • 1970-01-01
            • 2019-05-16
            相关资源
            最近更新 更多