遍历熊猫系列和格式日期

时间:2019-09-23 22:14:30

标签: python pandas

我需要从pandas系列中提取所有项目,这样才能在本地重新创建 在我的环境中。

当我遍历系列时,结果不允许重新创建。

当我查看系列项目时,我得到:

ser

2016-07-01     0
2016-07-04     1
2016-07-05     2
2016-07-06     3
2016-07-07     4
2016-07-08     5
2016-07-11     6
2016-07-12     7
2016-07-13     8
2016-07-14     9
2016-07-15    10

当我遍历它时:

for items in ser.iteritems(): 
             print(items)

(Timestamp('2016-07-01 00:00:00'), 0)
(Timestamp('2016-07-04 00:00:00'), 1)
(Timestamp('2016-07-05 00:00:00'), 2)
(Timestamp('2016-07-06 00:00:00'), 3)
(Timestamp('2016-07-07 00:00:00'), 4)
(Timestamp('2016-07-08 00:00:00'), 5)
(Timestamp('2016-07-11 00:00:00'), 6)
(Timestamp('2016-07-12 00:00:00'), 7)
(Timestamp('2016-07-13 00:00:00'), 8)
(Timestamp('2016-07-14 00:00:00'), 9)
(Timestamp('2016-07-15 00:00:00'), 10)

我需要有一个系列(即 ['2016-07-01','2016-07-04'.......''2016-07-15']),我可以将其分配为pd.Series

谢谢您能提供帮助

1 个答案:

答案 0 :(得分:0)

给出以下pd.Series

s=pd.Series(index=['2016-07-01', '2016-07-04','2016-07-05'], data=range(0,3))

2016-07-01    0
2016-07-04    1
2016-07-05    2

还有您的format_date函数:

def format_date(string_date):
    # format your date
    formatted_date = string_date.replace('-','/') #pd.to_datetime(string_date) 
    return formatted_date

此代码适合您:

s = pd.Series(index= s.index.map(format_date), data=s.values)

并返回索引格式为日期的系列:

2016/07/01    0
2016/07/04    1
2016/07/05    2