Python | Pandas Series.str.swapcase()
Last Updated :
17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas provide a method to swap case of each string in a series. This means lower case characters will be converted into uppercase and Uppercase character into lower case in every string. .str has to be prefixed every time before calling this method to differentiate it from Python’s default function otherwise, it will give an error.
This method works similarly to the str.upper() and str.lower() in Pandas.
Syntax: Series.str.swapcase()
Return Type: Series with Swapped case of each character
To download the CSV used in code, click here.
In the following examples, the data frame used contains data of some NBA players. As it can be seen, the text in data frame is mostly in Camel case. In the following examples, str.swapcase() method will be used to interchange case of the text. The image of data frame before any operations is shown below:
Example #1:
In this example, Null rows are removed using dropna() method (All though str.swapcase() doesn’t throw an error for null values, but it’s a good practice to remove them to avoid errors).
After that, the case of Text in Team column have been swapped using .swapcase() method and the results are overwritten in the Team column itself. After that, the Data frame is displayed to view the changes made in the text case of Team column.
import pandas as pd
data.dropna(how = 'all' , inplace = True )
data[ "Team" ] = data[ "Team" ]. str .swapcase()
data
|
Output:
As shown in the output image, the text case in Team column has been interchanged.
Example #2:
In this example, a copy of Name column is made. After that str.swapcase() is applied twice on it and it is checked with original Series that whether it’s same or not.
import pandas as pd
data.dropna(how = 'all' , inplace = True )
new = data[ "Team" ].copy()
data[ "Team" ] = data[ "Team" ]. str .swapcase(). str .swapcase()
filter = new = = data[ "Team" ]
data.where( filter )
|
Output:
As shown in the output image, the whole data frame was returned when the filter was passed in .where() method. This means after that after doing str.swapcase() twice, the string becomes what it was before operation.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...