0

If there is a column called date in a pandas.DataFrame, For which the values are:

'2018-02-01', 
'2018-02-02',
 ...

How do I change all the values to integers? For example:

'20180201', 
'20180202',
 ...
1
  • 1
    .replace the dashes with empty strings. Commented Mar 30, 2018 at 0:54

1 Answer 1

4

You can use .str.replace() like:

Code:

df['newdate'] = df['date'].str.replace('-', '')

or if not using a regex, faster as a list comprehension like:

df['newdate'] = [x.replace('-', '') for x in df['date']]

Test Code:

df = pd.DataFrame(['2018-02-01', '2018-02-02'], columns=['date'])
print(df)

df['newdate'] = df['date'].str.replace('-', '')
print(df)

df['newdate2'] = [x.replace('-', '') for x in df['date']]
print(df)

Results:

         date
0  2018-02-01
1  2018-02-02

         date   newdate
0  2018-02-01  20180201
1  2018-02-02  20180202

         date   newdate  newdate2
0  2018-02-01  20180201  20180201
1  2018-02-02  20180202  20180202
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.