Python | Pandas Series.str.len ()

Python Methods and Functions

str.len() Pandas str.len() is used to determine the length of each line in a row pandas This method is only for a sequence of lines. 
Since this is a string method, you must add the prefix .str before calling this method. Otherwise it will give an error.

Syntax: Series.str.len()

Return type: Series of integer values. NULL values ​​might be present too depending upon caller series.

To upload the CSV used in the code, click here.

In the following examples, the data frame used contains data for some NBA players. An image of the data frame before any operations is attached below. 

Example # 1: Calculating the length of a row of lines (dtype = str)

This example computes the row length of the Name column using the str.len () method. D Series is already a string. Thus, there is no need for data type conversion. Zero lines are removed before any operations are performed to avoid errors.

# pandas module import

import pandas as pd

 
# read CSV file from URL

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# remove null columns to avoid errors

data.dropna (inplace = True )

 
# create a new column for len
# pass values ​​through str.len ()

data [ "Name Length" ] = data [ " Name " ]. str . len ()

 
# display
data

Output:
As shown in the output image, the length of each row in the name column is returned. 

Notes :

  • This method does not account for the length of an integer or a floating point number. This will give an error as it is not a series of lines. The series must be converted first (shown in the following example)
  • There is no parameter to handle null values. A zero value will also return zero in the output string.

Example # 2:
In this example, the length of the salary column is calculated using the str.len ( ). Since the batch is imported as a float64 dtype, it is first converted to a string using the .astype () method.

# pandas module import

import pandas as pd

  
# read CSV file from URL

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# remove null columns to avoid errors

data.dropna (inplace   = True )

 
# convert to dtype string

data [ "Salary" ] = data [ "Salary" ]. astype ( str )

 
# passing values ​​

data [ "Salary Length" ] = data [ "Salary" ]. str . len ()

  
# convert back to popup dtype

data [ "Salary" ] = data [ "Salary" ]. astype ( float )

 
# display
data

Output:
As shown in the output, the length of an int or float series can only be calculated by converting it to a string of type d. 





Get Solution for free from DataCamp guru