简体   繁体   English

试图在 Python Pandas 中实现 join / vlookup(更新)

[英]Trying to achieve join / vlookup in Python Pandas (Updated)

Disclaimer: I am brand new to SO and Python.免责声明:我对 SO 和 Python 是全新的。

I am trying to convert my SQL left join query to python.我正在尝试将我的 SQL 左连接查询转换为 python。

Example:例子:

df1 is a dataframe which contains the columns: City, Event, date df1 是 dataframe 包含以下列:城市、事件、日期

df2: City, Zip Code, State, Country, etc. df2:城市,Zip 代码,State,国家等。

SQL: SQL:

SELECT Events.City, Events.Event, Events.Date, Masterlist.State, Masterlist.Country, Masterlist.[Zip Code]
FROM Events LEFT JOIN Masterlist ON Events.City = Masterlist.City

PYTHON: PYTHON:

df1 = pd.read_csv('Events.csv')

df2 = pd.read_csv('Masterlist.csv')

df3 = df1.join(df2, how='left')

df3 output: df3 output:

City, Event, date, Zip Code, State, Country

Fremont, Charity, 6/11, 99999, CA, US

Oakland, Protest, 6/11, 99998, CA, US

Fremont, Concert, 6/12, null, null, null

Oakland, Concert, 6/12, null, null, null

Ideal output is that it references df2 and returns the value based on City.It is currently only returning it for the first found value with that City.理想的 output 是它引用 df2 并返回基于 City 的值。它目前仅返回该 City 的第一个找到的值。 How can I get it to populate with its respective State, Zip Code, and Country for each row item?如何让它填充每个行项目的相应 State、Zip 代码和国家/地区?

You didn't specify on, I believe the below works:您没有指定,我相信以下方法有效:

import pandas as pd


df1 = pd.DataFrame({'City':["Tucson","Tucson","Portland","San Diego"], 
                    "Event":[1,5,3,2], 
                     "date":[1,2,3,4]})
df2 = pd.DataFrame({"City":["San Diego", "Tucson", "Portland"], 
                    "zip":[1,2,3], "state":["CA", "AZ", "OR"], 
                    "country":["USA","USA","USA"]})
pd.merge(df1,df2, how="left", on="City")

It is also best to provide a minimal dataset (like I did above) to make it easy for people to work with and help you out.最好提供一个最小的数据集(就像我上面所做的那样),以便人们可以轻松地与您合作并帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM