python - 如何使用 Python 中的其他列值创建新列?
问题描述
我需要Period_Subcategory
根据其他列的值创建一个列: { Period
value: [list of Sub_Category
values...]}的字典
输入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'}
解决方案
编写一个构造字典的函数并将其应用于您的数据框,按类别分组:
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)
推荐阅读
- php - 计算图像中任意颜色质心并将其提供给 PHP 的最快方法
- python - 如何迭代 Django 模型字段,并根据条件添加值
- html - 将图像定位在屏幕左侧
- linux - 如何返回默认的 Android Studio 工具栏?
- python - 使用关系运算符元素对 numpy 数组的多个索引进行操作
- javascript - .net core web api post使用fetch出现500错误
- python - 如何在 django 通用视图中本地化日期字段
- javascript - 正则表达式验证电话号码分机
- javascript - 如何将对象数组从创建的函数复制到Vue中的数据
- xcode - Xcode - 如果使用撤销按钮创建,如何将私钥添加到开发证书