Home > Backend Development > Python Tutorial > How to Replace Commas with Dashes in a Pandas Dataframe Column?

How to Replace Commas with Dashes in a Pandas Dataframe Column?

Patricia Arquette
Release: 2024-10-29 03:05:30
Original
281 people have browsed it

How to Replace Commas with Dashes in a Pandas Dataframe Column?

Replacing Text in a Pandas Dataframe Column

When working with data in a Pandas dataframe, it can be necessary to manipulate the values within columns. One common task is replacing text, such as commas with dashes.

If you have a column with values like:

range
"(2,30)"
"(50,290)"
"(400,1000)"
...
Copy after login

And want to replace the commas with dashes, the following method can be used:

df['range'].replace(',', '-', inplace=True)
Copy after login

However, this method may not always produce the desired result. Instead, it is recommended to use the vectorized str method replace, as follows:

df['range'] = df['range'].str.replace(',','-')
Copy after login

This code will successfully replace all commas with dashes in the 'range' column.

It's important to note that the original method you tried did not work because the string values in the 'range' column did not exactly match the comma character. The str.replace method performs a more precise match and replaces the appropriate characters.

The above is the detailed content of How to Replace Commas with Dashes in a Pandas Dataframe Column?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template