从datafram中的列创建排列

2024-09-27 07:23:52 发布

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

嗨,我有一个数据帧,如下所示:

enter image description here

并希望创建包含2列的数据帧:

写入器1写入器2

上面列出了一首歌的所有编剧:在《03邦妮与克莱德》中,作者包括:普林斯、图帕克·沙库尔、杰伊·兹、泰龙·赖斯和坎耶·韦斯特。因此,我的数据帧应该如下所示:

Writer1 Writer2

Prince  Tupac Shakur

Prince  Jay-Z

Prince  Tyrone Wrice

Prince  Kanye West

Tupac S Jay-Z

Tupac S Tyrone Wrice

Tupac S Kanye West

Jay-Z   Tyrone Wrice

Jay-Z   Kanye West

Tyrone  Kanye West

你知道我该怎么做吗?在


Tags: 数据作者westprince编剧jaywriter2tyrone
1条回答
网友
1楼 · 发布于 2024-09-27 07:23:52

下面是一种使用itertools.combinations的方法:

import itertools
import pandas as pd

def get_combinations(df, song_name):
    """
    Get a dataframe of all two-writer combinations for a given song.

    :param df: dataframe containing all artists, songs and writers
    :param song_name: name of song 
    :returns: dataframe with cols 'Writer1', 'Writer2' of all two writer combinations for the given song
    """
    song_frame = df[df['Song'] == song_name]
    combinations_df = pd.DataFrame(list(itertools.combinations(song_frame['Writer'].unique(), 2)), 
                                   columns=['Writer1', 'Writer2'])
    return combinations_df

combinations_df = get_combinations(df, '03 Bonnie & Clyde')

请注意,这假设您的数据是Pandas数据帧的形式。您可以轻松地从文本文件或csv中读入,或创建一个类似于以下内容的文件进行测试:

^{pr2}$

如果您想在整个数据帧上有效地应用此功能,请考虑:

def combinations_per_group(group):
    """Return combinations of writers after grouping by song."""     
    group_combs = pd.DataFrame(list(itertools.combinations(group['Writer'].unique(),2)),
                               columns=['Writer1', 'Writer2'])
combinations_df = df.groupby(['Song']).apply(combinations_per_group)\
                    .reset_index()\
                    .drop('level_1', axis=1)

这将返回一个数据帧,其中以歌曲为索引,所需的列给出了每首歌曲的所有编剧组合。在

相关问题 更多 >

    热门问题