Home > database >  how do you concatenated column value for row in pandas data frame?
how do you concatenated column value for row in pandas data frame?

Time:09-03

I am trying to create a new column with concatenated values from other columns in each row of my dataframe:

here is my current attempt

dataFrame['images/0'] = 'https://img.ssensemedia.com/images/b_white,g_center,f_auto,q_auto:best/'   str(dataFrame['sku'])   '_'   '0'   dataFrame['name']

but this is creating a column with values from all of the other rows too. How do I create a new column for each row from the other values of a row? I cant find a definite answer anywhere.

CodePudding user response:

I would try with apply():

dataFrame['images/0'] = dataFrame.apply(lambda x: f"https://img.ssensemedia.com/images/b_white,g_center,f_auto,q_auto:best/{x['sku']}_0{x['name']}", axis=1)

By setting axis=1 it will pass row by row to lambda so you can access individual column values with x['column_name'].

CodePudding user response:

This will work:

df = pd.DataFrame([["test_sku", "test_name"]], columns=["sku", "name"])

df['images0'] = df.apply(lambda x: 'https://img.ssensemedia.com/images/b_white,g_center,f_auto,q_auto:best/'   str(x['sku'])   '_'   '0'   x['name'], axis=1)

The output dataframe looks like this:

        sku       name                                            images0
0  test_sku  test_name  https://img.ssensemedia.com/images/b_white,g_c...
  • Related