基于基于字符串的层次结构为列赋值



我正在尝试在Pandas数据帧中创建一个新列,其中比较了两列,并根据预定义的层次结构在比较两列后填充第三列。新列将根据层次结构采用两者中较高的列。层次结构从最高到最低如下:

A1
A2
A3
A4
A5  

数据帧df如下所示。

sales_code   price_bucket_a   price_bucket_b
101          A1               A2
102          A3               A4
202          A2               A3
201          A4               A5
301          A2               A2 
302          A5               A1

我试图实现的所需输出如下所示。

sales_code   price_bucket_a   price_bucket_b   price_bucket_hier
101          A1               A2               A1
102          A3               A4               A3
202          A2               A3               A2
201          A4               A5               A4
301          A2               A2               A2
302          A5               A1               A1

有问题的层次结构和数据帧只是总数的一个片段。

任何人可以提供的任何帮助将不胜感激。

首先我们需要转换为类别,然后我们可以做minmax来获得正确的答案

cat=['A1','A2','A3','A4','A5']
df[['price_bucket_a','price_bucket_b']].apply(lambda x : pd.Categorical(x, categories=cat,ordered=True )).min(axis=1)
0    A1
1    A3
2    A2
3    A4
4    A2
dtype: object

以下是IIUC的一种方法:

ix = df.filter(like='price').apply(lambda x: x.str.lstrip('A')).astype(int).idxmin(1)
df['price_bucket_hier'] = df.lookup(range(df.shape[0]), ix)

print(df)
sales_code price_bucket_a price_bucket_b price_bucket_hier
0         101             A1             A2                A1
1         102             A3             A4                A3
2         202             A2             A3                A2
3         201             A4             A5                A4
4         301             A2             A2                A2

最新更新