[英]Assign value to a column based on a string-based hierarchy
我正在嘗試在比較兩列的 Pandas DataFrame 中創建一個新列,並根據預定義的層次結構在比較兩列之后填充第三列。 新列將根據層次結構采用兩者中較高的一個。 層次結構從最高到最低如下:
A1
A2
A3
A4
A5
DataFrame 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
所討論的層次結構和 DataFrame 只是總體總數的一小部分。
任何人都可以提供的任何幫助將不勝感激。
首先我們需要轉換為類別然后我們可以做min
或max
來得到正確的答案
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.