![]() |
We are given a dataframe in Pandas with multiple columns, and we want to apply string methods to transform the data within these columns. In this article, we will explore three different approaches to applying string methods to multiple columns of a dataframe. Apply String Methods to Multiple Columns of a DataframeBelow are the possible approaches to apply string methods to multiple columns of a dataframe in Python:
Apply String Methods To Multiple Columns Of A Dataframe Using applymapIn this example, we are using the applymap function to apply the str.lower method to all elements in the specified columns (‘name‘ and ‘city‘). This converts all string values in these columns to lowercase.
Output name city 0 horje noida 1 codingforall san francisco 2 codewars los angeles Apply String Methods To Multiple Columns Of A Dataframe Using apply with lambdaIn this example, we are using the apply method with a lambda function to apply the str.upper method to each element in the ‘name‘ and ‘city‘ columns. This converts all string values in these columns to uppercase.
Output name city 0 GEEKSFORGEEKS NOIDA 1 CODINGFORALL SAN FRANCISCO 2 CODEWARS LOS ANGELES Apply String Methods To Multiple Columns Of A Dataframe Using assign with str accessorIn this example, we are using the assign method with the str accessor in pandas to apply the capitalize string method to the ‘name‘ and ‘city‘ columns of the dataframe, converting the first letter of each word to uppercase.
Output name city 0 Geeksforgeeks Noida 1 Codingforall San francisco 2 Codewars Los angeles |
Reffered: https://www.geeksforgeeks.org
Pandas |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |