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

Pandas多级索引打印问题:如何每行显示完整日期时间索引

多级索引打印时重复显示所有层级值的解决方法

问题场景

将DataFrame的Date和Time列设为多级索引后,打印输出时Date仅在首行显示,后续行仅展示Time,需要每行都完整显示Date和Time的内容。

原DataFrame格式

Date    Time    Accum.  Scatter...
2020-12-30  10:37:04    3   0.789...
2020-12-30  10:37:07    3   0.814...
2020-12-30  10:37:10    3   0.787...
2020-12-30  10:37:13    3   0.803...
2020-12-30  10:37:16    3   0.798...
2020-12-30  10:37:19    3   0.818...
2020-12-30  10:37:22    3   0.809...

当前打印输出

55... 
Date       Time                                                                                                                                                                                                                                                          
2020-12-30 10:37:04  0.000000 ...
           10:37:07  0.000000 ...
           10:37:10  0.000000 ...
           10:37:13  0.000000 ...
           10:37:16  0.000000 ...

现有代码

df = pd.read_csv('UHSAS 20201230c.txt',delimiter=r'\s+',engine = 'python')
df.set_index(['Date', 'Time'],inplace=True)

concentration = df.iloc[:,13:].div(df.Sample,axis=0)

print(concentration.to_string())

解决方法

方法1:保留多级索引,修改打印参数

直接调整to_string()的参数,强制显示所有索引层级的完整值:

print(concentration.to_string(sparsify=False, index_names=True))
  • sparsify=False:关闭多级索引的稀疏显示逻辑,让每行都输出所有索引层级的内容
  • index_names=True:确保索引的名称(Date、Time)正常显示

方法2:重置索引为普通列

如果后续无需使用多级索引进行数据操作,可以将索引转回普通列,输出格式会和原DataFrame一致:

concentration = df.iloc[:,13:].div(df.Sample,axis=0).reset_index()
print(concentration.to_string())

内容的提问来源于stack exchange,提问作者doctor strange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:40:19