Search code examples
pythonpandaspandas-loc

Pandas Create New Column Based Off of Condition and Value in Other Column


I have a data set like the following:

ID Type
1   a  
2   a  
3   b  
4   b 
5   c

And I'm trying to create the column URL as shown by specifying a different URL based on the "Type" and appending the "ID".

ID Type URL
1   a  http://example.com/examplea/id=1
2   a  http://example.com/examplea/id=2
3   b  http://example.com/bbb/id=3
4   b  http://example.com/bbb/id=4
5   c  http://example.com/testc/id=5

I'm using something like this for the code but it is not pulling in the ID for just that row, instead it is appending all the IDs that have Type = a.

df.loc[df['Type'] == 'a', 'URL']= 'http://example.com/examplea/id='+str(df['ID'])
df.loc[df['Type'] == 'b', 'URL']= 'http://example.com/bbb/id='+str(df['ID'])

Solution

  • You should alter the command a bit:

    df.loc[df['Type'] == 'a', 'URL']= 'http://example.com/examplea/id='+df['ID'].astype(str)
    df.loc[df['Type'] == 'b', 'URL']= 'http://example.com/bbb/id='+df['ID'].astype(str)
    

    Or you can use map like this:

    url_dict = {
        'a':'http://example.com/examplea/id=',
        'b':'http://example.com/bbb/id=',
        'c':'http://example.com/testc/id='
    }
    
    df['URL'] = df['Type'].map(url_dict) + df['ID'].astype(str)
    

    Output:

       ID Type                               URL
    0   1    a  http://example.com/examplea/id=1
    1   2    a  http://example.com/examplea/id=2
    2   3    b       http://example.com/bbb/id=3
    3   4    b       http://example.com/bbb/id=4
    4   5    c     http://example.com/testc/id=5