2

I have a Python array in the form:

K = [ [2022,1,16], [2022,1,18], [2022,2,12], [2022,3,24]]

This array contains dates within sub-arrays.

How can I turn it into a Pandas DataFrame with 1 column of dates in standard format (%d/%m/%Y)?

2
  • 1
    In Python, those are called lists, not arrays. Anyway - did you try reading the documentation? Did you try to write any kind of call to the DataFrame constructor? What happened when you tried this, and how was the result different from what you wanted? Also, what does this have to do with machine learning? Please only tag things that are relevant to the problem you are actively asking about, not the project that motivates the question. Commented Feb 2, 2022 at 23:09
  • Welcome back to Stack Overflow. As a refresher, please read How to Ask and meta.stackoverflow.com/questions/261592. Commented Feb 2, 2022 at 23:10

2 Answers 2

1
import pandas as pd
date_array = [ [2022,1,16], [2022,1,18], [2022,2,12], [2022,3,24]]
date_df = pd.DataFrame(date_array, columns=['year', 'month', 'day'])
date_df['date'] = pd.to_datetime(date_df[['year', 'month', 'day']], format='%d/%m/%Y')

And if you'd like you can drop extra columns

Sign up to request clarification or add additional context in comments.

Comments

1
import datetime
K = [ [2022,1,16], [2022,1,18], [2022,2,12], [2022,3,24]]
dict_t ={"date": []}
import  pandas as pd
for time_list in K:
  dict_t["date"] += [datetime.datetime(*time_list)]
pd.DataFrame(dict_t)
#output
    date
0   2022-01-16
1   2022-01-18
2   2022-02-12
3   2022-03-24

you can change the format this way

import datetime
K = [ [2022,1,16], [2022,1,18], [2022,2,12], [2022,3,24]]
dict_t ={"date": []}
import  pandas as pd
for time_list in K:
  dict_t["date"] += [datetime.datetime(*time_list)]
df = pd.DataFrame(dict_t)
df.style.format({"date": lambda t: t.strftime("%d/%m/%Y")})

    date
0   16/01/2022
1   18/01/2022
2   12/02/2022
3   24/03/2022

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.