0

I have a Pandas df that looks something like this:

|       df      |    y    |
| ------------- | ------- |
| [30, 2018M01] | [50956] |
| [30, 2018M02] | [48561] |
| [30, 2018M03] | [36487] |

I want to transform it to:

|     df     |   y   |
| ---------- | ----- |
| 2018-01-01 | 50956 |
| 2018-02-01 | 48561 |
| 2018-03-01 | 36487 |

In other words transforming the strings with extract and replace. How would I go about doing this?

1
  • What are the types of the df and y columns? Feb 15, 2021 at 10:19

1 Answer 1

0

It there are lists use:

df['df'] = pd.to_datetime(df['df'].str[1], format='%YM%m')
df['y'] = df['y'].str[0]

It there are strings use:

df['df'] = pd.to_datetime(df['df'].str.strip('[]').str.split(', ').str[1], format='%YM%m')
df['y'] = df['y'].str.strip('[]')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.