通过列中的标记列表对数据帧行进行分组的有效方法

2024-09-29 19:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

给定如下数据帧:

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]

我目前的代码可以工作,但我想知道是否有更有效的方法来实现这一点。 例如

  • 不需要在list、dataframe和dictionary之间进行转换
  • 不需要使用for循环(可能类似于groupby
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')

Tags: thegamedffordatafistarsci
1条回答
网友
1楼 · 发布于 2024-09-29 19:35:25

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

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]

相关问题 更多 >

    热门问题