Maphanew Kim
Maphanew Kim

Reputation: 49

Python how to replace a column's values in dataframe

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',
 ...

Upvotes: 0

Views: 78

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49862

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

Upvotes: 4

Related Questions