How can you delete text within a column in pandas?

To remove text from a column of data, you can utilize the str.replace() method.

Firstly, use the str.replace() method to replace the text you want to delete with an empty string. Then, assign the replaced result back to the original column.

Here is a sample code:

import pandas as pd

# 创建示例数据
data = {'col1': ['apple', 'banana', 'orange'],
        'col2': ['apple123', 'banana456', 'orange789']}

df = pd.DataFrame(data)

# 删除col2列中的文字
df['col2'] = df['col2'].str.replace(r'\D+', '')

print(df)

Output result:

     col1 col2
0   apple  123
1  banana  456
2  orange  789

In the example above, we used the regular expression r’\D+’ to match non-numeric characters. We replaced the matched characters with an empty string, effectively deleting them.

Note: In the above example, we assigned the replaced result to the original column df[‘col2’]. If you wish to keep the original column and create a new column to store the replaced result, you can use df[‘new_col’] = df[‘col2′].str.replace(r’\D+’, ”).

bannerAds