String methods in Pandas
In this tutorial, we will learn some of the most commonly used string methods in Pandas. These string methods are applied to a series in Pandas. These methods are mainly used for string manipulation. So, let’s begin the tutorial.
Series in Pandas
We will consider the following series.
import pandas as p data1 = (['heLLo','weLcoMe','to','COdespeedy']) d1 = p.Series(data1) print(d1)
OUTPUT:
0 heLLo 1 weLcoMe 2 to 3 COdespeedy dtype: object
1) upper() method in Python pandas
This method is used to convert the series to uppercase.
import pandas as p data1 = (['heLLo','weLcoMe','to','COdespeedy']) d1 = p.Series(data1) print(d1.str.upper())
OUTPUT:
0 HELLO 1 WELCOME 2 TO 3 CODESPEEDY dtype: object
2) lower() method
This method is used to convert the series to lowercase.
import pandas as p data1 = (['heLLo','weLcoMe','to','COdespeedy']) d1 = p.Series(data1) print(d1.str.lower())
OUTPUT:
0 hello 1 welcome 2 to 3 codespeedy dtype: object
3) len() method
This method is used to return the length of each element in the series.
import pandas as p data1 = (['heLLo','weLcoMe','to','COdespeedy']) d1 = p.Series(data1) print(d1.str.len())
OUTPUT:
0 5 1 7 2 2 3 10 dtype: int64
4) isdigit() method
This method is used to check if the elements of the series are digits or not. If it is a digit, it returns True, otherwise, it returns False.
import pandas as p data1 = (['heLLo','weLcoMe','to','COdespeedy']) d1 = p.Series(data1) print(d1.str.isdigit())
OUTPUT:
0 False 1 False 2 False 3 False dtype: bool
5) match() method
This method is used to match a particular string with all the elements of the series. If the string matches with an element, it returns True. Otherwise, it returns False. Here, we will match the string “COdespeedy” with all the elements of the series.
import pandas as p data1 = (['heLLo','weLcoMe','to','COdespeedy']) d1 = p.Series(data1) print(d1.str.match('COdespeedy'))
OUTPUT:
0 False 1 False 2 False 3 True dtype: bool
Leave a Reply