Home > Blockchain >  How can I convert an array of dates into a Pandas DataFrame?
How can I convert an array of dates into a Pandas DataFrame?

Time:02-03

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)?

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • Related