0

I have a dataset with a column "date" with values like "Jul 31, 2014", "Sep 23, 2018"... I want to place months in a different column, convert them in integer using "df.to_datetime(df.MONTH, format='%b').dt.month" and then return back in order to sort it by the date index.

How can I choose only the first 3 letters from the cells?

Ksenia
  • 49
  • 4
  • Please be a bit more specific when asking a question: *What have you tried so far with a code example?* / *What do you expect?* **For Help take a look at "[How to ask](//stackoverflow.com/help/how-to-ask)"** – rizerphe May 09 '20 at 06:57

1 Answers1

1

You can try to_datetime with the date format %b %d, %Y:

df["date"] = pd.to_datetime(df["date"], format='%b %d, %Y')
df["month"] = df["date"].dt.month

Code:

print(df)
#            date
# 0  Jul 31, 2014
# 1  Sep 23, 2018

df["date"] = pd.to_datetime(df["date"], format='%b %d, %Y')
df["month"] = df["date"].dt.month
print(df)
#         date  month
# 0 2014-07-31      7
# 1 2018-09-23      9

For more detail on how to get the date format, refer the doc

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
  • Thank You a lot! Could you also explain how to get a value with a certain position from a cell? I guess I'll need it in the future. – Ksenia May 09 '20 at 07:53
  • That sounds as a new topic. It's better to only ask one specific problem per question and solve them when you have the answer. See [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). For some advice on how to select a cell, see [How to get a value from a cell of a dataframe?](https://stackoverflow.com/questions/16729574/how-to-get-a-value-from-a-cell-of-a-dataframe) – Alexandre B. May 09 '20 at 07:57