Home > Back-end >  PANDAS : join a string with a part of a string from another column
PANDAS : join a string with a part of a string from another column

Time:08-05

I have a data-frame:

df1 = pd.DataFrame({'ShipTo': ["", "", "", ""], 'Item_Description':["SYD_QANTAS ", "SYD_QANTAS", "PVG_SHANGHAI", "HKG_JARDINE"]})

I'd like to create a string merge in the column ShipTo "B" first 3 characters from the column "Item_Description" so the result would be:

enter image description here

How can I do that?

CodePudding user response:

TRy this,

df["ShipTo"] = "B" df1['Item_Description'].str[:3]

O/P:

  ShipTo Item_Description
0   BSYD      SYD_QANTAS 
1   BSYD       SYD_QANTAS
2   BPVG     PVG_SHANGHAI
3   BHKG      HKG_JARDINE

Slice first 3 elemnts of Item Description column and merge with your string literal.

CodePudding user response:

Or with str.slice():

df1["ShipTo"] = "B"   df1['Item_Description'].str.slice(stop=3)

prints:

  ShipTo Item_Description
0   BSYD      SYD_QANTAS 
1   BSYD       SYD_QANTAS
2   BPVG     PVG_SHANGHAI
3   BHKG      HKG_JARDINE
  • Related