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

如何将一个DataFrame中的值匹配至另一个DataFrame并添加对应列

解决方案:给行程DataFrame添加区域列

我来帮你搞定这个问题!这里有两种简单可行的方案,你可以根据自己的场景选择:

方法1:用map()配合自定义函数补全

你之前写的getZone函数只差最后一步啦,我们可以完善它,然后用map()把行程表的每个站点对应到区域:

import pandas as pd

# 先模拟你的两个DataFrame(替换成你实际的变量名)
trips = pd.DataFrame({
    'Origin': ['Victoria', 'Wembley', 'Canary Wharf', 'Stratford'],
    'Coordinates': ['x,y', 'x,y', 'x,y', 'x,y'],
    'Time': ['15:32', '14:00', '11:00', '09:00']
})

stations = pd.DataFrame({
    'Station': ['Victoria', 'Waterloo', 'Stratford'],
    'Zone': [1, 1, 2]
})

def getZone(station_name):
    # 匹配站点并返回对应的区域,找不到则返回None(你也可以改成'Unknown'之类的自定义值)
    match_result = stations[stations['Station'] == station_name]['Zone']
    return match_result.iloc[0] if not match_result.empty else None

# 给trips添加OriginZone列
trips['OriginZone'] = trips['Origin'].map(getZone)

注意:这个方法适合需要自定义处理无匹配情况的场景,比如给找不到的站点标注特定值。

方法2:用merge()关联数据(更高效简洁)

如果你的数据量比较大,用pandas的merge()方法会更高效,它专门用于数据表之间的关联匹配:

# 左连接保留trips的所有行,按Origin和Station列匹配
trips_with_zone = trips.merge(stations, left_on='Origin', right_on='Station', how='left')

# 重命名Zone列为OriginZone,并删除多余的Station列
trips_with_zone.rename(columns={'Zone': 'OriginZone'}, inplace=True)
trips_with_zone.drop('Station', axis=1, inplace=True)

这个方法的优势是代码更简洁,处理大规模数据时性能更好。如果有站点找不到匹配,对应的OriginZone会显示NaN,你可以用fillna()方法统一填充,比如:

trips_with_zone['OriginZone'] = trips_with_zone['OriginZone'].fillna('Unknown')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:33:17