Converting a pandas Series with Timestamps to strings is rather simple, eg:
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')
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
您可以使用以下方法将所有内容转换为DataFrame中的字符串:
df = df.astype(str)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.