Monday, 29 January 2024

Pandas: Get length of each string in a given column

'len()' method return the length of each string in a given column.

Example

df['No_of_chars_in_city'] = df['City'].str.len()

As you see above snippet, we are using 'str' accessor to perform the string operations. 'df['City'].str.len()' calculates the length of each string in the 'City' column and creates a new column 'No_of_chars_in_city' with the respective lengths.

 

Find the below working application.

 

len.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['krishna gurram', 'sailu nava', 'joel chelli', 'chamu mag', 'Jitendra khod', "Krishna battu"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [67, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df['No_of_chars_in_city'] = df['City'].str.len()

print('\nDataFrame after adding new column NoOfCharsInCity\n', df)

Output

Original DataFrame
             Name  Age       City  Gender  Rating
0  krishna gurram   34  Bangalore    Male      67
1      sailu nava   35  Hyderabad  Female      43
2     joel chelli  234  Hyderabad    Male      67
3       chamu mag   35    Chennai  Female     100
4   Jitendra khod   52  Bangalore    Male      41
5   Krishna battu   34    Chennai    Male      89

DataFrame after adding new column NoOfCharsInCity
              Name  Age       City  Gender  Rating  No_of_chars_in_city
0  krishna gurram   34  Bangalore    Male      67                    9
1      sailu nava   35  Hyderabad  Female      43                    9
2     joel chelli  234  Hyderabad    Male      67                    9
3       chamu mag   35    Chennai  Female     100                    7
4   Jitendra khod   52  Bangalore    Male      41                    9
5   Krishna battu   34    Chennai    Male      89                    7

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment