pandas 将带有时间戳的熊猫数据帧转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45931946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:20:40  来源:igfitidea点击:

Convert pandas dataframe with Timestamps to String

pythonpandasdataframe

提问by afora377

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

将带有时间戳的Pandas系列转换为字符串非常简单,例如:

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:

但是你如何转换一个所有列都是日期的大Pandas数据框。以上不适用于:

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

回答by jezrael

You can use apply:

您可以使用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

回答by Nathan S

You can convert everything to strings in the DataFrame using:

您可以使用以下方法将 DataFrame 中的所有内容转换为字符串:

df = df.astype(str)