You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中基于两字符串列条件创建changeInLocation新列

Adding the changeInLocation Column to Your Location Data

Got it, let's walk through how to create the required changeInLocation column based on your specified rules.

Rule Recap

  • Set to 0: When the pastLocation value exists anywhere in the comma-separated currentLocation list (including exact matches where both values are identical)
  • Set to 1: When pastLocation is not present in currentLocation at all

Row-by-Row Validation

Let's verify each entry to make sure we're applying the rule correctly:

  • Row 1: delhi vs bangalore → delhi isn't in bangalore → changeInLocation = 1
  • Row 2: delhi vs london,pune,delhi → delhi is explicitly in the list → changeInLocation = 0
  • Row 3: mumbai vs mumbai → Exact match, so mumbai is present → changeInLocation = 0
  • Row 4: pune vs pune, noida → pune is the first entry in the list → changeInLocation = 0

Final Formatted Output

pastLocation | currentLocation | changeInLocation
delhi | bangalore | 1
delhi | london,pune,delhi | 0
mumbai | mumbai | 0
pune | pune, noida | 0

Bonus: Python (Pandas) Implementation

If you're working with this data programmatically, here's a quick pandas snippet to generate the column automatically:

import pandas as pd

# Initialize the data
location_data = {
    "pastLocation": ["delhi", "delhi", "mumbai", "pune"],
    "currentLocation": ["bangalore", "london,pune,delhi", "mumbai", "pune, noida"]
}
df = pd.DataFrame(location_data)

# Function to calculate the change value
def get_location_change(past, current):
    # Split current locations, clean up whitespace, check for presence
    cleaned_current = [loc.strip() for loc in current.split(",")]
    return 0 if past in cleaned_current else 1

# Apply the function to create the new column
df["changeInLocation"] = df.apply(lambda row: get_location_change(row["pastLocation"], row["currentLocation"]), axis=1)

# Output in pipe-separated format
print(df.to_csv(sep="|", index=False))

内容的提问来源于stack exchange,提问作者Mighty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:13:27