Swap the case in column of the python Dataframe – pandas swapcase()

In this tutorial we will be using swapcase() function in pandas to swap the cases of the character column in the dataframe. swapcase() function in pandas converts all the uppers case to lower cases and all the lower cases to upper cases. lets see an example of swapcase() function in pandas python.

  • If the input string is in small case it swaps the result to upper case.
  • If the input string is in upper case it swaps the result to small case.
  • If input string is in mix of small case and upper case then it swaps all the upper case character to small case and all the small case character to upper case.

Lets look it with an Example

Create dataframe:

## create dataframe

import pandas as pd
d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'],
     'Description' : ['First Quarter of the year', 'second quarter of the year', 'Third  Quarter of the year', 'FOURTH QUARTER OF THE YEAR']}
df=pd.DataFrame(d)
print df

resultant dataframe will be

Swap the case in column of the python Dataframe - pandas 1

# swapcase function in python to swap the case 

df['swapped_desc'] = map(lambda x: x.swapcase(), df['Description'])
print df

swap function simply swaps the case of each and every character in the string and stores it in the swapped_desc column of the dataframe, so the output will be

Swap the case in column of the python Dataframe - pandas 2

 

previous Swap the case in column of the python Dataframe - pandas                                                                                                          next Swap the case in column of the python Dataframe - pandas

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.