We help IT Professionals succeed at work.

Extract substring from dataframe and add it to new column.

Newton
Newton asked
on
Medium Priority
79 Views
Last Modified: 2020-03-02
How to extract a substring from column and add it back as new column.

For example, I have file1 with 2 column. I want extract first 3 character from fullname column and then I need to add it as new column.

File1
FullName|count
APPLE|100
ORANG|200
GRAPES|300

I need below output
Output1
FullName|ShortName|count
APPLE |APP|100
ORANGE |ORA|200
GRAPES|GRA|300

Is below is correct way of doing this.
Script
df = pd.read_csv('File1', sep='|')
df['ShortName'] = df['FullName'].str.slice[0:3]
df.out_csv('output1')
Comment
Watch Question

Excel & VBA Expert
CERTIFIED EXPERT
Most Valuable Expert 2018
Awarded 2015
Commented:

You may try it like this...

df['ShortName'] = df['FullName'].str.slice(stop=3)


Or something like this...

df['ShortName'] = df['FullName'].str[:3]


Author

Commented:
Thank You Neeraj. Your solution solved my problem.
Subodh Tiwari (Neeraj)Excel & VBA Expert
CERTIFIED EXPERT
Most Valuable Expert 2018
Awarded 2015

Commented:
You're welcome Newton! Glad it worked as desired.