how to remove 5 last characters of a string for ach row in pandas in python

To remove the last 5 characters of a string in each row of a pandas dataframe column, you can use the str.slice method. Here's an example:

main.py
import pandas as pd

# Example dataframe
data = {'col1': ['abcdef', 'ghijkl', 'mnopqr']}
df = pd.DataFrame(data)

# Remove last 5 characters
df['col1'] = df['col1'].str.slice(stop=-5)

# Print updated dataframe
print(df)
221 chars
12 lines

This will give the following output:

main.py
  col1
0   abc
1   ghi
2   mno
31 chars
5 lines

In the above code, the str.slice method is used to remove the last 5 characters from each string in the 'col1' column of the dataframe. The stop parameter is set to -5 to remove the characters from the end of the string.

related categories

gistlibby LogSnag