0

I am trying to replicate some code on Datacamp which works fine on their platform and is ticked as correct but throws an error for me on my jupyter notebook.

Below is the info on the DF in question:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 132 entries, 0 to 131
Data columns (total 3 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   year         132 non-null    int64  
 1   month        132 non-null    object 
 2   unempl_rate  123 non-null    float64
dtypes: float64(1), int64(1), object(1)
memory usage: 3.2+ KB

Here is the code that doesn't work:

df['date'] = pd.to_datetime(df['year'] + '-' + df["month"])

Doing this gives a similar error:

df['date'] = pd.to_datetime(df['year'] + '-' + df["month"].astype(str))

Both columns are Dtype "object". The year column is just numbers and the month column are in format "jan, "feb", "mar" etc.

I get an error of the type "TypeError:

unsupported operand type(s) for +: 'int' and 'str'"

I also seem to get another type of error when trying which is:


UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')

Any ideas what I could be doing wrong and why it works for Datacamp IDE but not for me I would be thankful!

Alex28034
  • 47
  • 6
  • 1
    try `df['year'].astype(str) + df['month']`, basically converting the int into str – Derlin Aug 25 '20 at 17:59
  • Does this answer your question? [How to combine year, month, and day columns to single datetime column?](https://stackoverflow.com/questions/48155787/how-to-combine-year-month-and-day-columns-to-single-datetime-column) – Trenton McKinney Aug 25 '20 at 18:06
  • Please see [How to provide a reproducible copy of your DataFrame using `df.head(30).to_clipboard()`](https://stackoverflow.com/questions/52413246), then **[edit] your question**, and paste the clipboard into a code block. Always provide a [mre] **with code, data, errors, current output, and expected output, as text**. Only plot images are okay. – Trenton McKinney Aug 25 '20 at 18:26
  • YES Thanks Derlin! That worked and makes total sense. – Alex28034 Aug 25 '20 at 18:26

1 Answers1

0

Try converting to str:

df['date'] = pd.to_datetime(df['year'].astype(str) + '-' + df["month"].astype(str))
NYC Coder
  • 7,424
  • 2
  • 11
  • 24