2

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
  • 2
    number_pandas['date'].astype(str).str.replace(".", "-", regex=False)? Commented Feb 5, 2021 at 13:49

1 Answer 1

1

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
>>> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.