我正在嘗試根據一些特定的“規則”創建一個列。我想在“結果”末尾有一個新列,其中包含基于前三個列的以下結果:
| is_return | 從 | 到 | 結果 |
|---|---|---|---|
| 真的 | 冷杉 | 有限元 | 冷杉 |
| 錯誤的 | 特雷 | 西夫 | 特雷西夫 |
| 真的 | 西夫 | 特雷 | TreSyv_r |
| 錯誤的 | 特雷 | 西夫 | TreSyv2 |
| 真的 | 西夫 | 特雷 | TreSyv_r2 |
| 錯誤的 | 斯諾 | 范 | 斯諾凡 |
基本上,如果有一個不是回傳的旅行,那么只需組合 from 和 to,如果有多個(第 4 行),則添加一個從 2 開始的數字。如果它被標記為回程,則首先檢查它是否作為非回程存在,如第 2 行和第 3 行中給出的示例。但如果它被標記為回傳而沒有存在不回程變體,則保持此格式不變(第 1 行)。
uj5u.com熱心網友回復:
IIUC,您需要幾個步驟(在代碼中注釋):
import numpy as np
# compute the string for both directions
s1 = df['From'] df['To']
s2 = df['To'] df['From']
# compute the string is the correct order
# depending on the existence of the first trip
s = pd.Series(np.where(s2.isin(s1[~df['is_return']]), s2 '_r', s1),
index=df.index)
# add number to duplicates
count = s.groupby(s).cumcount().add(1)
df['Result'] = s np.where(count.gt(1), count.astype(str), '')
輸出:
is_return From To Result
0 True Fir Fem FirFem
1 False Tre Syv TreSyv
2 True Syv Tre TreSyv_r
3 False Tre Syv TreSyv2
4 True Syv Tre TreSyv_r2
5 False Sn? Van Sn?Van
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459179.html
