如何“漂亮地打印”Python pandas DatetimeIndex?

6

我刚接触pandas,对它的功能感到十分惊奇,但有时我也很惊讶它的一些做法;-)

我写了一个小脚本,用于报告时间序列中遇到的缺失值的数量,可以是每个月或每年的系列数据。以下是使用一些虚拟数据进行演示的代码。

如果我打印返回的结果(print cntyprint cntm),一切看起来都很好,除了我希望按照我的数据分辨率格式化索引的日期时间值,即我希望在年度输出中得到2000 1000 10 15而不是2000-12-31 1000 10 15,在月度输出中得到2000-01 744 10 15。在pandas中有没有简单的方法可以做到这一点,或者我必须通过一些循环将其转换为“普通” Python?注意:我事先不知道有多少数据列,因此任何基于每行固定格式字符串的东西对我都无效。

import numpy as np
import pandas as pd
import datetime as dt


def make_data():
    """Make up some bogus data where we know the number of missing values"""
    time = np.array([dt.datetime(2000,1,1)+dt.timedelta(hours=i)
                     for i in range(1000)])
    wd = np.arange(0.,1000.,1.)
    ws = wd*0.2
    wd[[2,3,4,8,9,22,25,33,99,324]] = -99.9   # 10 missing values
    ws[[2,3,4,10,11,12,565,644,645,646,647,648,666,667,669]]  =-99.9 # 15 missing values
    data = np.array(zip(time,wd,ws), dtype=[('time', dt.datetime),
                                            ('wd', 'f4'), ('ws', 'f4')])
    return data


def count_miss(data):
    time = data['time']
    dff = pd.DataFrame(data, index=time)
    # two options for setting missing values:
    # 1) replace everything less or equal -99
    for c in dff.columns:
        ser = pd.Series(dff[c])
        ser[ser <= -99.] = np.nan
        dff[c] = ser
    # 2) alternative: if you know the exact value to be replaced
    # you can use the DataFrame replace method:
##    dff.replace(-99.9, np.nan, inplace=True)

    # add the time variable as data column
    dff['time'] = time
    # count missing values
    # the print expressions will print date labels and the total number of values
    # in the time column plus the number of missing values for all other columns
    # annually:
    cnty = dff.resample('A', how='count', closed='right', label='right')
    for c in cnty.columns:
        if c != 'time':
            cnty[c] = cnty['time']-cnty[c]
    # monthly:
    cntm = dff.resample('M', how='count', closed='right', label='right')
    for c in cntm.columns:
        if c != 'time':
            cntm[c] = cntm['time']-cntm[c]
    return cnty, cntm

if __name__ == "__main__":
    data = make_data()
    cnty, cntm = count_miss(data)

最后提示:虽然DatetimeIndex有一种格式方法,但不幸的是没有解释如何使用它。
2个回答

9
DatetimeIndexformat方法与datetime.datetime对象的strftime方法类似。这意味着您可以使用在此处找到的格式字符串:http://www.tutorialspoint.com/python/time_strftime.htm。 诀窍在于,您必须传递format方法的 formatter关键字参数。例如:
import pandas
dt = pandas.DatetimeIndex(periods=10, start='2014-02-01', freq='10T')
dt.format(formatter=lambda x: x.strftime('%Y    %m    %d  %H:%M.%S'))

输出:

['2014    02    01  00:00.00',
 '2014    02    01  00:10.00',
 '2014    02    01  00:20.00',
 '2014    02    01  00:30.00',
 '2014    02    01  00:40.00',
 '2014    02    01  00:50.00',
 '2014    02    01  01:00.00',
 '2014    02    01  01:10.00',
 '2014    02    01  01:20.00',
 '2014    02    01  01:30.00']

0

这取决于你想要多漂亮,但对于大多数用例来说,它非常简单:

print(date[0])(其中date是你的DatetimeIndex变量)。

你将得到如下输出:

2019-04-26 12:00:00


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接