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

Python:将列表转为Pandas DataFrame,实现指定列重复值空白显示

实现tabulate输出时ATM列仅首行显示值

问题场景

现有Python代码及数据结构如下:

print_hr()
ATMITMData('Bank Nifty')
print_hr()
print(bn_strikes)
print(tabulate(pd.DataFrame(bn_strikes), headers='keys', tablefmt='psql', showindex=False))

其中bn_strikes的结构为:

{'ATM': 40800, 'ITM': [40700, 40600, 40500], 'OTM': [40900, 41000, 41100]}

当前tabulate输出的表格为:

+-------+-------+-------+
|   ATM |   ITM |   OTM |
|-------+-------+-------|
| 40800 | 40700 | 40900 |
| 40800 | 40600 | 41000 |
| 40800 | 40500 | 41100 |
+-------+-------+-------+

需要实现ATM列仅首行显示值,其余重复行显示为空的效果:

+-------+-------+-------+
|   ATM |   ITM |   OTM |
|-------+-------+-------|
| 40800 | 40700 | 40900 |
|       | 40600 | 41000 |
|       | 40500 | 41100 |
+-------+-------+-------+

此前尝试用drop_duplicates会删除后续行,不符合需求。

解决方案

通过修改DataFrame的ATM列,将除首行外的重复值替换为空字符串,再用tabulate输出:

import pandas as pd
from tabulate import tabulate

# 构造目标DataFrame
df = pd.DataFrame(bn_strikes)
# 仅保留ATM列首行的值,其余行替换为空
df['ATM'] = df['ATM'].where(df.index == 0, '')
# 输出格式化表格
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False))

说明

  • df.index == 0 精准定位表格首行,where方法会保留满足条件行的原值,不满足条件的行则替换为指定的空字符串。
  • 该方法既保留了所有数据行,又实现了ATM列仅首行显示值的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:37:08