我试图根据一些特定的"规则"创建一个列。我希望在末尾有一个新列"Result"根据前三列得到以下结果:
<表类>
is_return
与
结果
tbody><<tr>对 杉木 有限元 FirFem 假 混乱关系 Syv TreSyv 真正Syv 混乱关系 TreSyv_r 假 混乱关系 Syv TreSyv2 真正Syv 混乱关系 TreSyv_r2 假 Snø Van SnøVan 表类>
现在,您需要几个步骤(在代码中注释):
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