Nur Atiqah
Nur Atiqah

Reputation: 105

How to remove certain string from column in pandas dataframe

I want to remove a certain keywords or string in a column from pandas dataframe.

The dataframe df looks like this:

YEAR    WEEK
2019    WK-01
2019    WK-02
2019    WK-03
2019    WK-14
2019    WK-25
2020    WK-06
2020    WK-07

I would like to remove WK-and 0 from the WEEK column so that my output will looks like this:

YEAR    WEEK
2019    1
2019    2
2019    3
2019    14
2019    25
2020    6
2020    7

Upvotes: 0

Views: 89

Answers (2)

timgeb
timgeb

Reputation: 78650

Shave off the first three characters and convert to int.

df['WEEK'] = df['WEEK'].str[3:].astype(int)

Upvotes: 3

Quang Hoang
Quang Hoang

Reputation: 150735

You can try:

df['WEEK'] = df['WEEK'].str.extract('(\d*)$').astype(int)

Output:

   YEAR  WEEK
0  2019     1
1  2019     2
2  2019     3
3  2019    14
4  2019    25
5  2020     6
6  2020     7

Upvotes: 3

Related Questions