w3resource

Pandas Data Series: Replace missing white spaces in a given string with the least frequent character

 


Write a Pandas program to replace missing white spaces in a given string with the least frequent character.

Sample Solution :

Python Code :

import pandas as pd
str1 = 'abc def abcdef icd'
print("Original series:")
print(str1)
ser = pd.Series(list(str1))
element_freq = ser.value_counts()
print(element_freq)
current_freq = element_freq.dropna().index[-1]
result = "".join(ser.replace(' ', current_freq))
print(result)

Sample Output:

Original series:
abc def abcdef icd
c    3
     3
d    3
f    2
e    2
a    2
b    2
i    1
dtype: int64
abcidefiabcdefiicd

Explanation:

str1 = 'abc def abcdef icd': Stores a string in a variable 'str1'.

ser = pd.Series(list(str1)): This code takes the string ‘str1’ and converts it into a Pandas Series object ser. The list() function is used to split the string into individual characters and create a list of characters, which is then used to create the Pandas Series object.

element_freq = ser.value_counts(): Here, the code creates a Pandas Series object 'element_freq' that contains the frequency of each unique element in the 'ser' series using the value_counts() function. The resulting series is sorted in descending order of frequency.

current_freq = element_freq.dropna().index[-1]: This code extracts the most frequent element from the 'element_freq' series using the dropna() and index() functions, and stores it in the variable 'current_freq'.

result = "".join(ser.replace(' ', current_freq)): Finally, the code replaces all the spaces in the 'ser' series with the 'current_freq' element using the replace() function, and then joins the resulting series back into a string using the join() function.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to find the positions of the values neighboured by smaller values on both sides in a given series.
Next: Write a Pandas program to compute the autocorrelations of a given numeric series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.