[英]Indexing and matching rows between two different dataframes using Pandas in Python
这里的第一个问题,所以请让我知道是否需要进一步说明。 本质上,我有两个数据帧,我需要索引/匹配(基本上是Excel中的vLookUp),但无法使其终身有效。
我有两个数据框。
df_1 = pd.DataFrame([['55555', '975 8th Avenue', ""],
['44444', '900 Market St', ""],
['54444', '975 7th Avenue', ""],
['44445', '901 Market St', ""],
['33333', '975 4th Avenue', ""],
['35555', '975 8th Avenue', ""]], columns=['storezipCode', 'streetAddress', 'storeLoc'])
和
df_2 = pd.DataFrame([['New York', '53333'],
['New York', '54444'],
['New York', '55555'],
['San Francisco', '44443'],
['San Francisco', '44444'],
['San Francisco', '44445'],
['Chicago', '33333'],
['Chicago', '34444'],
['Chicago', '35555']], columns=['storeLoc', 'storezipCode'])
我要完成的工作是从df_2中提取“ storeLoc”,并将其与df_1和df_2中的“ storezipCode”进行匹配。
实际上,就行/列而言,两帧数据远不相等,所以我认为这让我非常头疼。 有谁知道一个简单的解决方案吗? 在Excel中,这只是小菜一碟,所以我觉得我只是在忽略一些东西。
试试map
和set_index
:
df_1['storeLoc'] = df_1.storezipCode.map(df_2.set_index('storezipCode')['storeLoc'])
print(df_1)
输出:
storezipCode streetAddress storeLoc
0 55555 975 8th Avenue New York
1 44444 900 Market St San Francisco
2 54444 975 7th Avenue New York
3 44445 901 Market St San Francisco
4 33333 975 4th Avenue Chicago
5 35555 975 8th Avenue Chicago
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.