Search code examples
pythonpandasdataframehyperlinkextract

How to create another column in python pandas from the current table?


I have the following table:

ColumnA ColumnB ColumnC
1 AB001 TYPE-A
2 AB012 TYPE-A
3 AB035 TYPE-B
4 AB039 TYPE-B
5 AB065 TYPE-A
6 AB088 TYPE-B

I should get the output such that, if ColumnC is TYPE-A then it should save as a separate column (ColumnD) with output www.website.com/abc/AB001 if it is TYPE-B then it should be www.website.com/xyz/AB035. The output table should look like the following:

Output_should_look_like_this

How do I do that?


Solution

  • Use Series.map by dictionary for types strings and join together by +:

    #if no match `TYPE-A` or `TYPE-B` added default value no match
    s = df['ColumnC'].map({'TYPE-A':'abc','TYPE-B':'xyz'}).fillna('no match')
    df['ColumnD'] = ' www.website.com/' + s + '/' + df['ColumnB'].astype(str)
    print (df)
       ColumnA ColumnB ColumnC                     ColumnD
    0        1   AB001  TYPE-A   www.website.com/abc/AB001
    1        2   AB012  TYPE-A   www.website.com/abc/AB012
    2        3   AB035  TYPE-B   www.website.com/xyz/AB035
    3        4   AB039  TYPE-B   www.website.com/xyz/AB039
    4        5   AB065  TYPE-A   www.website.com/abc/AB065
    5        6   AB088  TYPE-B   www.website.com/xyz/AB088