Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas dataframe with Timestamps to String

Converting a pandas Series with Timestamps to strings is rather simple, e.g.:

dateSfromPandas = dfC['Date324'].dt.strftime('%Y/%m/%d')

But how do you convert a large pandas Dataframe with all columns being dates. The above does not work on:

dateSfromPandas = dfC.dt.strftime('%Y/%m/%d')
like image 318
afora377 Avatar asked Aug 29 '17 06:08

afora377


2 Answers

You can use apply:

dateSfromPandas = dfC.apply(lambda x: x.dt.strftime('%Y/%m/%d'))

Sample:

dfC = pd.DataFrame({'a': pd.date_range('2016-01-01', periods=10),
                    'b': pd.date_range('2016-10-04', periods=10),
                    'c': pd.date_range('2016-05-06', periods=10)})
print (dfC)
           a          b          c
0 2016-01-01 2016-10-04 2016-05-06
1 2016-01-02 2016-10-05 2016-05-07
2 2016-01-03 2016-10-06 2016-05-08
3 2016-01-04 2016-10-07 2016-05-09
4 2016-01-05 2016-10-08 2016-05-10
5 2016-01-06 2016-10-09 2016-05-11
6 2016-01-07 2016-10-10 2016-05-12
7 2016-01-08 2016-10-11 2016-05-13
8 2016-01-09 2016-10-12 2016-05-14
9 2016-01-10 2016-10-13 2016-05-15

dateSfromPandas = dfC.apply(lambda x: x.dt.strftime('%Y/%m/%d'))
print (dateSfromPandas)
            a           b           c
0  2016/01/01  2016/10/04  2016/05/06
1  2016/01/02  2016/10/05  2016/05/07
2  2016/01/03  2016/10/06  2016/05/08
3  2016/01/04  2016/10/07  2016/05/09
4  2016/01/05  2016/10/08  2016/05/10
5  2016/01/06  2016/10/09  2016/05/11
6  2016/01/07  2016/10/10  2016/05/12
7  2016/01/08  2016/10/11  2016/05/13
8  2016/01/09  2016/10/12  2016/05/14
9  2016/01/10  2016/10/13  2016/05/15

Another possible solution if want modify original:

for col in dfC:
    dfC[col] = dfC[col].dt.strftime('%Y/%m/%d')
print (dfC)
            a           b           c
0  2016/01/01  2016/10/04  2016/05/06
1  2016/01/02  2016/10/05  2016/05/07
2  2016/01/03  2016/10/06  2016/05/08
3  2016/01/04  2016/10/07  2016/05/09
4  2016/01/05  2016/10/08  2016/05/10
5  2016/01/06  2016/10/09  2016/05/11
6  2016/01/07  2016/10/10  2016/05/12
7  2016/01/08  2016/10/11  2016/05/13
8  2016/01/09  2016/10/12  2016/05/14
9  2016/01/10  2016/10/13  2016/05/15
like image 192
jezrael Avatar answered Nov 14 '22 21:11

jezrael


You can convert everything to strings in the DataFrame using:

df = df.astype(str)
like image 36
Nathan S Avatar answered Nov 14 '22 22:11

Nathan S