python - 从数据框中的列创建排列
问题描述
嗨,我有一个数据框如下:
并想创建一个包含 2 列的数据框:
作家1 作家2
列出了前一首歌曲作者的所有排列:对于歌曲 03 Bonnie & Clyde,作者: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
知道我该怎么做吗?
解决方案
这是使用的一种方法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)
这将返回一个数据框,其中歌曲作为索引,所需的列给出每首歌曲的所有作者组合。
推荐阅读
- javascript - 如何从字符串中删除除数字字符和小数点之外的每个字符
- winapi - 如何获得 d3d_aware 的 IMFTransform(将 Windows 复制 API 的输入编码为 H264)?
- html - 在 Angular 中使用 ngFor 正确显示数据
- mingw - MinGW 应用程序不接受任何用户输入
- selenium - 在黄瓜项目中使用另一种类方法的架构问题
- python - 如何显示数据框的 MultiIndex 对象?
- javascript - 如何使 Gridstack.js 小部件垂直响应?
- javascript - 无法将文件 POST 到 /upload
- php - 访问自定义 REST API 在正文中返回“可读流”而不是 json 数据
- ios - IOS Firebase Facebook 登录 FUIFacebookAuth 没有回调