我有以下格式的数据:
pastLocation | currentLocation
delhi | bangalore
delhi | london,pune,delhi
mumbai | mumbai
pune | pune, noida
我必须创建一个名为 changeInLocation
的新列,如果 pastLocation
出现在 currentLocation
中,那么新列的值将是 0
否则 1
。
例如,在第二行中,pastLocation
即德里出现在相应的 currentLocation
中,因此 changeInLocation
的值应为 0
输出应采用以下格式:
pastLocation | currentLocation | changeInLocation
delhi | bangalore | 1
delhi | london,pune,delhi | 0
mumbai | mumbai | 0
pune | pune, noida | 0
最佳答案
使用 apply
和 in
来检查成员资格,然后转换为 int
:
df['changeInLocation'] = df.apply(lambda x: x['pastLocation'] not in x['currentLocation'], axis=1).astype(int)
另一个解决方案是压缩列并使用列表理解
:
df['changeInLocation'] = [int(a not in b) for a, b in zip(df['pastLocation'], df['currentLocation'])]
print (df)
pastLocation currentLocation changeInLocation
0 delhi bangalore 1
1 delhi london,pune,delhi 0
2 mumbai mumbai 0
3 pune pune, noida 0
关于python - 根据从 python 中的其他两个字符串列应用的条件创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289998/