如何“漂亮打印”python pandas DatetimeIndex

2024-10-01 09:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我对熊猫还是个新手,对它能做的事还是很惊讶的,虽然有时也会对它的工作方式感到惊讶;—)

我设法编写了一个小脚本,它将报告在timeseries中遇到的缺失值的数量,无论是在该系列的每个月还是在该系列的每年。下面是使用一些虚拟数据进行演示的代码。在

如果我打印返回的结果(print cntyprint cntm),一切看起来都很好,除了我想根据数据的分辨率格式化索引的日期时间值,即我希望用2000 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的格式方法,但不幸的是没有解释如何使用它。在


Tags: theinfordatatimeascountnp
1条回答
网友
1楼 · 发布于 2024-10-01 09:20:01

DatetimeIndexformat方法的执行与datetime.datetime对象的strftime相似。在

这意味着您可以使用这里的格式字符串:http://www.tutorialspoint.com/python/time_strftime.htm

诀窍是必须传递formatterkwarg方法的formatterkwarg。这看起来像这样(就像一个与您的代码有些无关的示例:

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'))

输出:

^{pr2}$

相关问题 更多 >