简体   繁体   中英

Fetch data from another dataframe

I had asked a question earlier but it was closed as the initial question was considered as duplicate.

But I am trying to something different from that thread as well as duplicate thread.

String Replacement From Another DataFrame.

So please don't close this thread. Thanks.

I need to replace my column depending upon data from another dataframe. Have to search for respective "name" from the other dataframe and include the "change_name" in the df1

DataFrame 1:

ID  name
1   cat
2   jack
3   snake
4   monkey

DataFrame 2:

name    change_name
cat     meow
jack    oooo 
snake   ssss
monkey 
note    money
pencil pen

Expected Output:

ID  name
1   cat      meow
2   jack     oooo
3   snake    ssss
4   monkey   nan
5   note    money
6   pencil pen

I had to do like below:

def map_name(name):
    elif name == 'cat':
        return 'meow'
    elif name == 'jack':
        return 'oooo'
    elif name == 'snake':
        return 'ssss'
    elif name == 'monkey ':
        return None
    else
        return name

df1['name'] = df1['name'].apply(map_name)

As the list is small, I have hardcoded here but the list might grow. Can someone tell how to do the same functionality using dataframes? Thanks.

A simple merge would do it.
And then since you want the rows in df2 which are not in df1 concat them.

pd.concat([df1.merge(df2),df2[~df2['name'].isin(df1['name'])]]

Result:

In [23]: pd.concat([df1.merge(df2),df2[~df2['name'].isin(df1['name'])]])
Out[23]: 
    ID    name change_name
0  1.0     cat        meow
1  2.0    jack        oooo
2  3.0   snake        ssss
3  4.0  monkey        None
4  NaN    note       money
5  NaN  pencil         pen

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