将特定列信息移动到当前行下的新行

问题描述 投票:0回答:1

考虑这个 df:

data = { 'Name Type': ["Primary", "Primary", "Primary"],
         'Full Name': ["John Snow", "Daenerys Targaryen", "Brienne Tarth"], 
         'AKA': ["Aegon Targaryen", None, None],
         'LQAKA': ["The Bastard of Winterfell", "Mother of Dragons", None],
         'Other': ["Info", "Info", "Info"]}
df = pd.DataFrame(data)

如果每个主名称下方的 akas 和 lqakas 不是 None,我需要移动 akas 和 lqakas,并将名称类型指定为 AKA 或 LQAKA。如果为 None,则不应创建任何行。还有许多其他列(例如其他列)应将信息与主要名称保留在同一行中。所以预期的结果是:

名称类型 全名 其他
小学 约翰·斯诺 信息
又名 伊耿·坦格利安
L卡卡 临冬城的私生子
小学 丹妮莉丝·坦格利安 信息
L卡卡 龙之母
小学 布蕾妮·塔斯 信息
python pandas dataframe
1个回答
0
投票

您可以

melt
和后期处理:

out = (df.melt(['Name Type', 'Other'], ignore_index=False)
         .dropna(subset='value')
         .sort_index(kind='stable', ignore_index=True)
         .rename(columns={'value': 'Full Name'})
       )

# identify rows with "Full Name"
m = out['variable'].ne('Full Name')
# mask unwanted entries
out.loc[m, 'Name Type'] = out.pop('variable')
out.loc[m, 'Other'] = ''

输出:

  Name Type Other                  Full Name
0   Primary  Info                  John Snow
1       AKA                  Aegon Targaryen
2     LQAKA        The Bastard of Winterfell
3   Primary  Info         Daenerys Targaryen
4     LQAKA                Mother of Dragons
5   Primary  Info              Brienne Tarth
© www.soinside.com 2019 - 2024. All rights reserved.