Python | Pandas Series.str.swapcase()
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.
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:
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.
As shown in the output image, the text case in Team column has been interchanged.
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.
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course