基于来自两个列和另一个布尔列的字符串创建一个列



我试图根据一些特定的"规则"创建一个列。我希望在末尾有一个新列"Result"根据前三列得到以下结果:

<表类> is_return 与 结果 tbody><<tr>对杉木有限元FirFem假混乱关系SyvTreSyv真正Syv混乱关系TreSyv_r假混乱关系SyvTreSyv2真正Syv混乱关系TreSyv_r2假SnøVanSnø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

最新更新