Sai Rajesh Sai Rajesh - 5 months ago 13
Python Question

how to create url column dataframe using two column values in python pandas?

I have following dataframe.

company,compid,secid
a,a1,a2
b,b1,b2


I need output like following format

company,compid,secid,url
a,a1,a2,http://www.cssss.com/companydetails.aspx?compid=a1&secid=a2
b,b1,b2,http://www.cssss.com/companydetails.aspx?compid=b1&secid=b2


how to add column values in url column?

Answer

Use:

df['url'] = 'http://www.cssss.com/companydetails.aspx?compid=' +
             df.compid + '&secid=' + df.secid
print (df)
  company compid secid                                                url
0       a     a1    a2  http://www.cssss.com/companydetails.aspx?compi...
1       b     b1    b2  http://www.cssss.com/companydetails.aspx?compi...

I change url for testing:

df['url'] = 'http:aaa.aspx?compid=' + df.compid + '&secid=' + df.secid
print (df)
  company compid secid                               url
0       a     a1    a2  http:aaa.aspx?compid=a1&secid=a2
1       b     b1    b2  http:aaa.aspx?compid=b1&secid=b2

If dtypes of columns compid and secid is int, cast to str by astype:

df['url'] = 'http:aaa.aspx?compid='+df.compid.astype(str)+'&secid='+df.secid.astype(str)
print (df)
  company compid secid                               url
0       a     a1    a2  http:aaa.aspx?compid=a1&secid=a2
1       b     b1    b2  http:aaa.aspx?compid=b1&secid=b2

EDIT by comment:

If any of columns compid and secid contains NaN it can be empty string:

#code before
data3 = pd.merge(df1,df2,on='company', how='outer') 

print (data3)
  company compid secid
0       a     a1    a2
1       b     b1    b2
2       a     a1   NaN
3       b    NaN   NaN

data3.loc[~data3[['compid','secid']].isnull().any(1), 'url'] = 
'http:aaa.aspx?compid=' + data3.compid.astype(str) + '&secid=' + data3.secid.astype(str)

data3.fillna('', inplace=True)
print (data3)

  company compid secid                               url
0       a     a1    a2  http:aaa.aspx?compid=a1&secid=a2
1       b     b1    b2  http:aaa.aspx?compid=b1&secid=b2
2       a     a1                                        
3       b                                               
Comments