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)" ...
And want to replace the commas with dashes, the following method can be used:
df['range'].replace(',', '-', inplace=True)
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(',','-')
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!