【问题标题】:Multiindex instead of groupby多索引而不是 groupby
【发布时间】:2020-02-21 22:21:42
【问题描述】:

我正在深入研究 pandas 多索引,我想知道是否可以用多索引替换 groupby 迭代处理。

目前我使用这个功能

原始数据:

                       station_name station_code breaktype
0                               ABC         ABC1         N
1                   American Heroes         HERO         L
2                   American Heroes         HERO         N
3           American Movie Classics          AMC         L
4           American Movie Classics          AMC         N
5                     Animal Planet         ANPL         L
6                     Animal Planet         ANPL         N

目前我使用这个功能:

def createRegexPattern(df):
    df = df.copy()
    groups = df.groupby(["station_name", "station_code"])
    patterns = pd.DataFrame([], columns=["origional_index", "root_words", "pattern"])
    for key, group in groups:
        patterns = patterns.append(pd.DataFrame(
            {"origional_index": [group.index.to_list()], 
             "root_words": [key], 
             "pattern": [tuple(functools.reduce(lambda x,y: x + re.split('[\s,-]',y.strip()), key,[]))]}
        ))
    return patterns.reset_index(drop=True)

制作这个:

   origional_index                             root_words                                  pattern
0              [0]                            (ABC, ABC1)                              (ABC, ABC1)
1           [1, 2]                (American Heroes, HERO)                 (American, Heroes, HERO)
2           [3, 4]         (American Movie Classics, AMC)         (American, Movie, Classics, AMC)
3           [5, 6]                  (Animal Planet, ANPL)                   (Animal, Planet, ANPL)

我是否可以使用多索引来生成如下结果: 多索引的期望结果

                                                                                origional_index breaktype
    station_name                   station_code  pattern
0   ABC                            ABC1          (ABC, ABC1)                                    0         N
1   American Heroes                HERO          (American, Heroes, HERO)                       1         L
                                                                                                2         N
2   American Movie Classics        AMC           (American, Movie, Classics, AMC)               3         L
                                                                                                4         N
3   Animal Planet                  ANPL          (Animal, Planet, ANPL)                         5         L
                                                                                                6         N

这对 DataFrame 是否可行,或者我应该在前进时停下来......

【问题讨论】:

    标签: python pandas multi-index


    【解决方案1】:

    您可以使用.set_index 轻松获得类似的东西:

    In [64]: df.reset_index().set_index(["station_name", "station_code"])
    Out[64]:
                                          index breaktype
    station_name            station_code
    ABC                     ABC1              0         N
    American Heroes         HERO              1         L
                            HERO              2         N
    American Movie Classics AMC               3         L
                            AMC               4         N
    Animal Planet           ANPL              5         L
                            ANPL              6         N
    

    您也可以将breaktype 转换为以原始索引为标签的列,然后从组合索引中计算出您的标记:

    In [65]: df.reset_index().set_index(["station_name", "station_code", "breaktype"]).unstack()['index']
    Out[65]:
    breaktype                               L    N
    station_name            station_code
    ABC                     ABC1          NaN  0.0
    American Heroes         HERO          1.0  2.0
    American Movie Classics AMC           3.0  4.0
    Animal Planet           ANPL          5.0  6.0
    

    不过,我不知道其中任何一个实际上都比您的 .groupby 方法“更好”。

    【讨论】:

      【解决方案2】:

      您可以先创建pattern 列,然后使用set_index() 来实现您想要的输出:

      df['pattern'] = (df['station_name'].str.split() + df['station_code'].str.split()).apply(tuple).astype(str)
      
      df.reset_index().set_index(['station_name','station_code','pattern']).rename(columns={'index': 'original_index'})
      

      产量:

                                                                                     original_index breaktype
      station_name            station_code pattern                                                           
      ABC                     ABC1         ('ABC', 'ABC1')                                        0         N
      American Heroes         HERO         ('American', 'Heroes', 'HERO')                         1         L
                                           ('American', 'Heroes', 'HERO')                         2         N
      American Movie Classics AMC          ('American', 'Movie', 'Classics', 'AMC')               3         L
                                           ('American', 'Movie', 'Classics', 'AMC')               4         N
      Animal Planet           ANPL         ('Animal', 'Planet', 'ANPL')                           5         L
                                           ('Animal', 'Planet', 'ANPL')                           6         N
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-15
        • 2016-12-08
        • 2018-04-17
        • 2022-07-19
        • 1970-01-01
        • 2020-01-27
        • 2021-07-13
        • 1970-01-01
        相关资源
        最近更新 更多