-1

I have a dataframe test which has a column company. I have another dataframe bsr which has 2 columns, market and region, both contain the same data type.

I want to extract the region of each company.

For that I wrote the following code:

test['region'] = [for company in test['company']]

I am not able to get the correct syntax of how to look for that company in the market column of bsr dataframe as key and get it's region as value.

Any help would be appreciated!

Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31
Soumya Pandey
  • 321
  • 3
  • 19
  • [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/4046632) – buran Feb 23 '23 at 14:44

1 Answers1

0

Simple merge should add region to test DataFrame. In case when you don't have all markets in bsr and you don't want to loose these data from test, use parameter how='left' in merge.

test = pd.DataFrame({'company': ['A', 'B']})
bsr = pd.DataFrame({'market': ['A', 'B'], 'region': [1, 2]})
test_with_region = test.merge(bsr, left_on='company', right_on='market')

Also you can then get rid of market column from test_with_region