首页 > 解决方案 > 如何使用 Python 中的其他列值创建新列?

问题描述

我需要Period_Subcategory根据其他列的值创建一个列: { Periodvalue: [list of Sub_Categoryvalues...]}的字典

输入df

Period   Category    Sub_Category
FY18Q1   Clothing    Shirt    
FY18Q2   Clothing    Trouser
FY18Q1   Clothing    Shirt
FY18Q3   Clothing    Pant 
FY18Q1   Accessories Watch
FY18Q2   Accessories Muff
FY18Q2   Accessories Watch
FY18Q3   Accessories Chains

期望的输出df_output

Category    Period_Subcategory
Clothing    {'FY18Q1':'Shirt','FY18Q2':'Trouser','FY18Q3':'Pant'}
Accessories {'FY18Q1':'Watch','FY18Q2':['muff','Watch'],'FY18Q3':'Chains'}

标签: pythonpandas

解决方案


编写一个构造字典的函数并将其应用于您的数据框,按类别分组:

def make_dict(df):
    d = {}
    for period in sorted(set(df.Period)):
        d[period] = list(set(df.Sub_Category[df.Period == period]))
    return d

df_output = df.groupby('Category').apply(make_dict)

推荐阅读