When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement.
We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has number of useful methods and one of them is
str.split, it can be used with split to get the desired part of the string. To get the nth part of the string, first split the column by delimiter and apply str[n-1] again on the object returned, i.e.
Let’s make it clear by examples.
Code #1: Print a data object of the splitted column.
0 Geek1 1 Geek2 2 Geek3 3 Geek4 4 Geek5 dtype: object
Code #2: Print a list of returned data object.
['Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5']
Code #3: Print a list of elements.
['id', 'id', 'id', 'id', 'id']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.