【问题标题】:Print only seconds for unix time columns in pandas DataFramepandas DataFrame 中的 unix 时间列仅打印几秒钟
【发布时间】:2018-10-10 21:09:12
【问题描述】:

这是一个将部分烛台数据加载到 Pandas DataFrame 中的 sn-p。我感兴趣的是漂亮地打印 DataFrame 的内容。我希望两个毫秒的 unix 时间戳列以秒为单位显示。

这是原始数据:

rawData = {'t': 1525019820000, 'T': 1525019879999, 'o': '0.07282300', 'c': '0.07290700', 'h': '0.07293300', 'l': '0.07279800', 'v': '48.57300000'}

此代码为每个时间戳列输出完整日期:

import pandas as pd

rawData = {'t': 1525019820000, 'T': 1525019879999, 'o': '0.07282300', 'c': '0.07290700', 'h': '0.07293300', 'l': '0.07279800', 'v': '48.57300000'}

df = pd.DataFrame([rawData])
df['t'] = pd.to_datetime(df['t'], unit='ms') # converting unix ts to datetime
df['T'] = pd.to_datetime(df['T'], unit='ms')
print(df.to_string(justify='center', columns=['t','T','o','c','h','l','v'], header=['from','to','open','close','high','low','vol']))

输出:

          from                   to               open       close        high        low         vol     
0 2018-04-29 16:37:00 2018-04-29 16:37:59.999  0.07282300  0.07290700  0.07293300  0.07279800  48.57300000

如何只显示两个时间列的时间部分,而不是显示?

    from      to        open       close        high        low         vol     
0 16:37:00 16:37:59  0.07282300  0.07290700  0.07293300  0.07279800  48.57300000

【问题讨论】:

    标签: python python-3.x pandas unix-timestamp pretty-print


    【解决方案1】:

    可以使用formatters参数(docs):

    print(df.to_string(justify='center', columns=['t','T','o','c','h','l','v'],
                       formatters={'t': lambda x: '{:%H:%M:%S}'.format(pd.to_datetime(x, unit="D")),
                                   'T': lambda x: '{:%H:%M:%S}'.format(pd.to_datetime(x, unit="D"))},
                       header=['from','to','open','close','high','low','vol']))
    

    【讨论】:

    • 是的,这是我在您发布答案时正在编写的解决方案。感谢您的反应!
    【解决方案2】:

    解决方案是使用 DataFrame.to_string 方法的 formatters= parm。如记录的here。 Lambda 是在格式化程序字典中定义的,由原始列名作为键...

    formatters={'t': lambda x: x.strftime("%H:%M:%S"), 'T': lambda x: x.strftime("%H:%M:%S")}
    

    这是整个代码:

    import pandas as pd
    
    rawData = {'t': 1525019820000, 'T': 1525019879999, 'o': '0.07282300', 'c': '0.07290700', 'h': '0.07293300', 'l': '0.07279800', 'v': '48.57300000'}
    
    df = pd.DataFrame([rawData])
    df['t'] = pd.to_datetime(df['t'], unit='ms')
    df['T'] = pd.to_datetime(df['T'], unit='ms')
    print(df.to_string(justify='center', columns=['t','T','o','c','h','l','v'], header=['from','to','open','close','high','low','vol'],  formatters={'t': lambda x: x.strftime("%H:%M:%S"), 'T': lambda x: x.strftime("%H:%M:%S")}))
    

    哪个输出

        from      to        open       close        high        low         vol     
    0 16:37:00 16:37:59  0.07282300  0.07290700  0.07293300  0.07279800  48.57300000
    

    【讨论】:

      猜你喜欢
      • 2011-02-18
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2019-02-27
      • 1970-01-01
      • 2022-11-25
      相关资源
      最近更新 更多