how to delete part of string in pandas in python

To delete part of a string in a pandas DataFrame column, you can use the .str.replace() method. Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['John Doe', 'Jane Smith', 'Mark Johnson'],
        'Age': [30, 25, 35]}
df = pd.DataFrame(data)

# Delete part of string in 'Name' column
df['Name'] = df['Name'].str.replace('Johnson', '')

print(df)
266 chars
12 lines

This will remove the string 'Johnson' from the 'Name' column in the DataFrame, resulting in:

main.py
          Name  Age
0     John Doe   30
1  Jane Smith    25
2         Mark   35
80 chars
5 lines

In the example, we use the .str.replace() method to replace 'Johnson' with an empty string ('') in the 'Name' column. Note that this operation modifies the original DataFrame.

If you want to delete parts of a string using a specific pattern or regular expression, you can also use the .str.replace() method with regex. For more advanced string manipulations, you might consider using the .str.extract() method or applying a custom function to the column.

related categories

gistlibby LogSnag