pandas 熊猫日期到字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39578466/
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
pandas date to string
提问by ooolllooo
i have a datetime pandas.Series
. One column called "dates". I want to get 'i' element in loop like string.
我有一个约会时间pandas.Series
。一栏称为“日期”。我想像字符串一样在循环中获取 'i' 元素。
s.apply(lambda x: x.strftime('%Y.%m.%d'))
or
astype(str).tail(1).reset_index()['date']
or many other solutions don't work.
s.apply(lambda x: x.strftime('%Y.%m.%d'))
或
astype(str).tail(1).reset_index()['date']
或许多其他解决方案不起作用。
I just want a string like '2016-09-16'
(first datetime element in series) and not what is currently returned, which is:
我只想要一个类似'2016-09-16'
(系列中的第一个日期时间元素)的字符串,而不是当前返回的字符串,即:
ss = series_of_dates.astype(str).tail(1).reset_index()['date']
"lol = %s" % ss
lol = 0 2016-09-16\nName: date, dtype: object
lol = 0 2016-09-16\nName: date, dtype: object
I need just:
我只需要:
lol = 2016-09-16
lol = 2016-09-16
because I need
因为我需要
some string
% a , b , s ,d
some string
% a , b , s ,d
..... without even '/n' in a, b ,s ...
..... 在 a, b ,s 中甚至没有 '/n' ...
采纳答案by Thanos
In order to extract the value, you can try:
为了提取值,您可以尝试:
ss = series_of_dates.astype(str).tail(1).reset_index().loc[0, 'date']
using loc
will give you the contents just fine.
使用loc
会给你的内容就好了。
回答by jezrael
I think you can use strftime
for convert datetime
column to string
column:
我认为您可以strftime
用于将datetime
列转换为string
列:
import pandas as pd
start = pd.to_datetime('2015-02-24 10:00')
rng = pd.date_range(start, periods=10)
df = pd.DataFrame({'dates': rng, 'a': range(10)})
print (df)
a dates
0 0 2015-02-24 10:00:00
1 1 2015-02-25 10:00:00
2 2 2015-02-26 10:00:00
3 3 2015-02-27 10:00:00
4 4 2015-02-28 10:00:00
5 5 2015-03-01 10:00:00
6 6 2015-03-02 10:00:00
7 7 2015-03-03 10:00:00
8 8 2015-03-04 10:00:00
9 9 2015-03-05 10:00:00
s = df.dates
print (s.dt.strftime('%Y.%m.%d'))
0 2015.02.24
1 2015.02.25
2 2015.02.26
3 2015.02.27
4 2015.02.28
5 2015.03.01
6 2015.03.02
7 2015.03.03
8 2015.03.04
9 2015.03.05
Name: dates, dtype: object
Loop with Series.iteritems
:
for idx, val in s.dt.strftime('%Y.%m.%d').iteritems():
print (val)
2015.02.24
2015.02.25
2015.02.26
2015.02.27
2015.02.28
2015.03.01
2015.03.02
2015.03.03
2015.03.04
2015.03.05