Methods for String Data
So far, we have worked with numerical marks. But a Series can also contain text data.
For example:
names = pd.Series(["Amit", "Rahul", "Priya", "Neha"])
For string data, Pandas provides the .str accessor.
str.lower(): The str.lower() method converts all text values into lowercase.
For example:
names.str.lower()
output:
0 amit
1 rahul
2 priya
3 neha
dtype: object
str.upper(): The str.upper() method converts all text values into uppercase.
For example:
names.str.upper()
output:
0 AMIT
1 RAHUL
2 PRIYA
3 NEHA
dtype: object
str.title(): The str.title() method converts the first character of each word into uppercase.
For example:
names = pd.Series(["amit kumar", "rahul singh"])
names.str.title()
output:
0 Amit Kumar
1 Rahul Singh
dtype: object
str.strip(): The str.strip() method removes unnecessary spaces from the beginning and end of each string.
For example:
names = pd.Series([" Amit ", " Rahul", "Priya "])
names.str.strip()
output:
0 Amit
1 Rahul
2 Priya
dtype: object
This is particularly useful when cleaning text data.
str.replace(): The str.replace() method replaces a particular text or pattern with another value.
For example:
names = pd.Series(["Amit", "Rahul", "Priya"])
names.str.replace("Amit", "Aman")
output:
0 Aman
1 Rahul
2 Priya
dtype: object
str.contains(): The str.contains() method checks whether a particular text or pattern exists inside each value.
For example:
names = pd.Series(["Amit", "Rahul", "Anita", "Neha"])
names.str.contains("A")
output:
0 True
1 False
2 True
3 False
dtype: bool
It returns True for values containing "A" and False for the others.
str.startswith(): The str.startswith() method checks whether each string starts with the given value.
For example:
names = pd.Series(["Amit", "Rahul", "Anita", "Neha"])
names.str.startswith("A")
output:
0 True
1 False
2 True
3 False
dtype: bool
str.endswith(): The str.endswith() method checks whether each string ends with the given value.
For example:
names = pd.Series(["Amit", "Rahul", "Priya", "Neha"])
names.str.endswith("a")
output:
0 False
1 False
2 True
3 True
dtype: bool
str.len(): The str.len() method returns the number of characters in each string.
For example:
names = pd.Series(["Amit", "Rahul", "Priya"])
names.str.len()
output:
0 4
1 5
2 5
dtype: int64
str.split(): The str.split() method splits each string based on the separator we provide.
For example:
names = pd.Series(["Amit Kumar", "Rahul Singh"])
names.str.split(" ")
output:
0 [Amit, Kumar]
1 [Rahul, Singh]
dtype: object
For example, if the Series contains full names, we can use str.split(" ") to separate the first name and last name.