简体   繁体   中英

How to merge only on rows where there is no value in the rows of a certain column in pandas dataframe

I have the following dataframe df1,

    CompanyName      Country Ticker ....................
0   Apple Inc.       US      AAPL
1   Microsoft        US
2   Sony             US
3   DBS              SG      D05
4   Razer            HK      0700
5   General Electric US      GE

Then I have a list of all the company names with just their tickers tickerdf,

    CompanyName      Ticker 
0   Apple Inc.       AAPL
1   Microsoft        MSFT
2   Sony             SNE     
3   DBS              D05.SI
4   Razer            0700.HK
5   General Electric GE

If I wanted to merge, on the company name I would do,

mergeddf = pd.merge(df1,tickerdf,on=['CompanyName'], how='left')

But if I did that I would end up with all the Ticker values from tickerdf1 like this

    CompanyName      Country Ticker ....................
0   Apple Inc.       US      AAPL
1   Microsoft        US      MSFT
2   Sony             US      SNE
3   DBS              SG      D05.SI
4   Razer            HK      0700.HK
5   General Electric US      GE

But, I want it to retain the values from the df1, basically only merge on the rows where there is no data on the ticker column, the output should look like this.

    CompanyName      Country Ticker ....................
0   Apple Inc.       US      AAPL
1   Microsoft        US      MSFT
2   Sony             US      SNE
3   DBS              SG      D05
4   Razer            HK      0700
5   General Electric US      GE

Is it possible to only merge data on rows where the Ticker column is empty?

You can do fillna :

# Ticker by company
s = df2.set_index('CompanyName')['Ticker']

df['Ticker'] = df['Ticker'].fillna(df['CompanyName'].map(s) )

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