給定 df1 和 df2:
df1:
| ID | 物品 | 子項 |
|---|---|---|
| 1 | 52 | AAA |
| 2 | 52 | AAA |
| 3 | 55 | BAA |
| 4 | 77 | 民航局 |
| 5 | 77 | 民航局 |
| 6 | 77 | 民航局 |
| 7 | 77 | 出租車 |
| 8 | 77 | CAC |
df2:
| ID | 顏色 |
|---|---|
| 1 | #11 |
| 2 | #12 |
| 3 | #13 |
| 4 | #14 |
| 5 | #17 |
| 6 | #18 |
| 7 | #19 |
| 8 | #20 |
| 9 | #21 |
| 10 | #25 |
產生 df_result:
| ID | 物品 | 子項 | 顏色 |
|---|---|---|---|
| 1 | 52 | AAA | #11 |
| 2 | 52 | AAA | #11 |
| 3 | 55 | BAA | #11 |
| 4 | 77 | 民航局 | #11 |
| 5 | 77 | 民航局 | #11 |
| 6 | 77 | 民航局 | #11 |
| 7 | 77 | 出租車 | #12 |
| 8 | 77 | CAC | #13 |
id不重要。專案組中的每個新子專案都會獲得新的序列色號。每個新專案的顏色開始重新分配回#11。df2 將始終足夠長以涵蓋專案組中的唯一子專案。
我的直覺是使用groupbyon df1,然后merge每個組使用df2,但我需要代碼方面的幫助來實作這一點。
uj5u.com熱心網友回復:
我不確定,但我認為這就是你想要的
merged_df = pd.merge(
df1,df2, how="left", on="Id"
)
uj5u.com熱心網友回復:
嘗試:
df1["color"] = (df2.merge(df1["sub-item"].ne(df1.groupby("item")["sub-item"].transform("first"))
.cumsum()
.add(1)
.rename("id"),
how="right")["color"]
)
>>> df1
id item sub-item color
0 1 52 AAA #11
1 2 52 AAA #11
2 3 55 BAA #11
3 4 77 CAA #11
4 5 77 CAA #11
5 6 77 CAA #11
6 7 77 CAB #12
7 8 77 CAC #13
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/398126.html
標籤:Python 熊猫 加入 pandas-groupby 熊猫合并
上一篇:在Rdplyr中執行一對多連接
