首页 > 解决方案 > 如何将此数据框转换为所需的设计?

问题描述

我有一张如下表:

在此处输入图像描述

我必须比较personA和PersonB,很难用肉眼判断personA的花费是否少于或多于personB,因此我想动态(使用pandas)为每个amount_spent属性添加一个列,其中IF personA花费少于那个类别的人 B 然后把 Y... 我不确定如何在 pandas 中实现以下目标:

在此处输入图像描述

有人可以帮忙吗?

标签: pythonpython-3.xpandas

解决方案


假设列名结构相同,可以np.where这样使用:

x=['food','clothes','vehicles','gadgets']
for i in x:
    df['amount_spend_'+i+'_tag']=np.where(df['amount_spend_'+i+'_PersonA']<df['amount_spend_'+i+'_PersonB'],"Y","")

推荐阅读