Write a Python function to split the string based on delimiter and convert to series


The result for splitting the string with ’' delimiter and convert to series as,

0    apple
1    orange
2    mango
3    kiwi

To solve this, we will follow the below approach −

Solution 1

  • define a function split_str() which accepts two arguments string and delimiter

  • Create s.split() function inside delimiter value and store it as split_data

split_data = s.split(d)
  • Apply split_data inside pd.Series() to generate series data.

pd.Series(split_data)
  • Finally, call the function to return the result.

Example

Let’s check the following code to get a better understanding −

import pandas as pd
def split_str(s,d):
   split_data = s.split(d)
   print(pd.Series(split_data))
split_str('apple\torange\tmango\tkiwi','\t')

Output

0    apple
1    orange
2    mango
3    kiwi
dtype: object

Solution 2

  • Define a string and assign it to the data variable

data = 'apple\torange\tmango\tkiwi'
  • Set delimiter = ’

  • Create lambda function and set two variables x as a string, y as delimiter with expression as x.split(y) and store it as split_data

split_data = lambda x,y: x.split(y)
  • Call the function with data and delimiter values and save it as a result list

result = split_data(data,delimiter)
  • Convert the result list to series as,

pd.Series(result)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
data = 'apple\torange\tmango\tkiwi'
delimiter = '\t'
split_data = lambda x,y: x.split(y)
result = split_data(data,delimiter)
print(pd.Series(result))

Output

0    apple
1    orange
2    mango
3    kiwi
dtype: object

Updated on: 25-Feb-2021

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements