You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中仅显示Unix时间列的秒数并美化打印

没问题,我来帮你搞定这两个需求——把毫秒时间戳转成秒级显示,同时让DataFrame的打印输出更美观。下面是具体的实现步骤和代码:

解决方案步骤

1. 手动转换毫秒时间戳为秒级

Pandas默认会把大数值的时间戳自动解析为datetime类型,这不是你想要的效果。所以我们需要手动将't'和'T'列的毫秒值除以1000,得到秒级Unix时间戳,用整数除法还能避免出现浮点数。

2. 美化DataFrame的打印输出

可以通过to_string()方法自定义显示格式,或者调整Pandas全局显示选项,让输出更整洁易读。


完整代码实现

import pandas as pd

# 原始K线数据
rawData = {
    "t": 1525019820000, 
    "T": 1525019879999, 
    "o": "0.07282300", 
    "c": "0.07290700", 
    "h": "0.07293300", 
    "l": "0.07279800", 
    "v": "48.57300000"
}

# 转换为DataFrame
df = pd.DataFrame([rawData])

# 将毫秒时间戳转换为秒级整数
df['t'] = df['t'] // 1000
df['T'] = df['T'] // 1000

# 美化打印:自定义列宽、格式,隐藏索引
print(df.to_string(
    col_space=12,  # 设置每列的宽度,避免内容挤在一起
    float_format=lambda x: f"{x}" if isinstance(x, int) else f"{x:.8f}",
    index=False  # 不需要显示行索引
))

输出效果

运行后你会得到整洁的格式化输出,时间戳以秒级整数显示,价格和成交量的格式也更清晰:

t            T            o            c            h            l            v
   1525019820   1525019879   0.07282300   0.07290700   0.07293300   0.07279800   48.57300000

进阶美化(适合Jupyter环境)

如果是在Jupyter Notebook里运行,还可以用Pandas的style方法生成带样式的表格:

styled_df = df.style.set_table_styles([
    {'selector': 'th', 'props': [('text-align', 'center'), ('font-weight', 'bold')]},
    {'selector': 'td', 'props': [('text-align', 'center')]}
]).format({
    't': '{:.0f}',
    'T': '{:.0f}',
    'o': '{:.8f}',
    'c': '{:.8f}',
    'h': '{:.8f}',
    'l': '{:.8f}',
    'v': '{:.6f}'
})
display(styled_df)

内容的提问来源于stack exchange,提问作者Jean-Pierre Schnyder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:51:22