从数据框中的列创建排列

时间:2018-05-27 10:37:58

标签: python dataframe permutation

您好我有一个数据框如下:

enter image description here

并且想要创建一个包含2列的数据框:

Writer1 Writer2

列出了歌曲作者的所有排列:对于歌曲03 Bonnie&作家克莱德:Prince,Tupac Shakur,Jay-Z,Tyrone Wrice和Kanye West参与其中。因此,我的数据框应如下所示:

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

我知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

以下是使用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中读取,或者创建类似以下内容的文件来测试:

import numpy as np
df = pd.DataFrame({'Artist':np.repeat('Jay-Z',5).tolist() + ['David Bowie'] * 2 + ['List of the X Factor finalists] * 2,
                   'Song':np.repeat('03 Bonnie & Clyde',5).tolist() + ['Heroes'] * 4,
                   'Writer':['Prince', 'Tupac Shakur',
                             'Jaz-Z', 'Tyrone Wrice',
                             'Kanye West'] + ['David Bowie', 'Brian Eno'] * 2})

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

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)

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