How to use Regex in pandas DataFrame with Python

Viewed 162

I try to replace only one caracter of a string in a pandas columns. Concretly, I want to replace . by - in the "Date" columns

Here is my script :

import pandas as pd

number = {"date": [2002.04, 2002.05], "team": ["a", "b"]}
number_pandas = pd.DataFrame(number)
number_pandas

number_pandas.date.replace(".", "-")

Here is the output :

0    2002.04
1    2002.05
Name: date, dtype: float64

It does not work. Maybe you can help with Regex.

1 Answers

You can cast the column data to that of type str first, and then use a mere string replacement with

number_pandas['date'].astype(str).str.replace(".", "-", regex=False)

A Pandas test:

>>> import pandas as pd
>>> number = {"date": [2002.04, 2002.05], "team": ["a", "b"]}
>>> number_pandas = pd.DataFrame(number)
>>> number_pandas['date'].astype(str).str.replace(r".", "-", regex=False)
0    2002-04
1    2002-05
Name: date, dtype: object
>>> 
Related