首页 > 解决方案 > 通过列中的标签列表对熊猫数据框行进行分组的有效方法

问题描述

给定一个数据框,如:

df = pd.DataFrame(
        {
            'Movie':
            [
                'Star Trek',
                'Harry Potter',
                'Bohemian Rhapsody',
                'The Imitation Game',
                'The Avengers'
            ],
            'Genre':
            [
                'sci-fi; fiction',
                'fantasy; fiction; magic',
                'biography; drama; music',
                'biography; drama; thriller',
                'action; adventure; sci-fi'
            ]
        }
)

我想按“流派”列中的各个标签进行分组,并将电影收集为如下列表:

                                                 0
magic                               [Harry Potter]
sci-fi                   [Star Trek, The Avengers]
fiction                  [Star Trek, Harry Potter]
drama      [Bohemian Rhapsody, The Imitation Game]
fantasy                             [Harry Potter]
music                          [Bohemian Rhapsody]
thriller                      [The Imitation Game]
action                              [The Avengers]
biography  [Bohemian Rhapsody, The Imitation Game]
adventure                           [The Avengers]

我当前的代码有效,但我想知道是否有更有效的方法来做到这一点。例如

genre = df['Genre'].apply(lambda x: str(x).split("; ")).tolist()
movie = df['Movie'].tolist()
data = dict()
for m,genres in zip(movie, genre):
    for g in genres:
        try:
            g_ = data[g]
        except:
            data[g] = [m]
        else:
            g_.append(m)

for key,value in data.items():
    data[key] = [data[key]]

output = pd.DataFrame.from_dict(data, orient='index')

标签: pythonpandasdataframe

解决方案


当我们第一次将流派分成一个列表时会更容易

df['Genre'] = df.Genre.str.split('; ')
df.explode('Genre').groupby('Genre')['Movie'].apply(list)

输出

action                                [The Avengers]
adventure                             [The Avengers]
biography    [Bohemian Rhapsody, The Imitation Game]
drama        [Bohemian Rhapsody, The Imitation Game]
fantasy                               [Harry Potter]
fiction                    [Star Trek, Harry Potter]
magic                                 [Harry Potter]
music                            [Bohemian Rhapsody]
sci-fi                     [Star Trek, The Avengers]
thriller                        [The Imitation Game]

推荐阅读