简体   繁体   中英

How to join a column using two other columns?

I have one table that gives gives me a VALUE based on the Month and Type of Residential Property.

表格1

and I have a second table that also contains Month (Date of Sale (dd/mm/yyyy)) and Type of Residential Property. 表2 I would use Month and Date of Sale (dd/mm/yyyy) as an index to join VALUE on to table 2 but Dublin and non Dublin properties both get a date each. How can I link VALUE onto table 2 using both columns?

On option I thought of is to concatenate Month and Type of Residential Property to make a unique index but was hoping for a simpler method. Thanks!

What about using pandas.merge with on=['Month', 'Type of Residential Property ] ? This way you can merge both tables based on those variables, including the VALUE.

Here is an example with similar tables. Let's say your first table is as follows: df and your second table is: df2 . Then using df2.merge(df, on=['Month', 'Type of Residential Property']) will get you this final dataframe: final df . For this to work, you will need to rename the column Date of Sale in df2 to Month (or the reverse: rename the column Month in df to Date of Sale ).

Here is the code for this example:

df = pd.DataFrame({'Month':'2010-01-01', 'Type of Residential
Property': 'Dublin', 'UNIT': 'Base 2015=100', 'VALUE':96.1},
index=[1203])

df2 = pd.DataFrame({'Month':'2010-01-01', 'Adress': '5
Braemor Drive', 'Price': '343,000,000', 'Type of Residential
Property': 'Dublin'}, index=[0])

df2.merge(df, on=['Month', 'Type of Residential Property'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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