python - 根据从 python 中的其他两个字符串列应用的条件创建一个新列

标签 python python-3.x pandas

我有以下格式的数据:

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

最佳答案

使用 applyin 来检查成员资格,然后转换为 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/

相关文章:

python - 如何选择具有最小值且满足另一列 pandas 中的条件的所有行

python - 如何使用 .loc 语法创建新列?

Python NumPy : Efficiently get rows containing min value of column for each unique tuple of 3 other columns

Python:如何使用 OpenCV 在单击时从网络摄像头捕获图像

python - 多线程/多处理以避免响应超时

Python - 更新 GUI,使其始终使用更新后的列表

python - 使用 Python 将索引设置为 csv 文件中重复行值的组

python - 模块未找到错误 : No module named 'utils'

python - 如何按分隔符拆分列表项并在每个分隔项上调用函数?

python - Pandas 专栏: applying a function