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

Python中如何用.format输出数据形状?解决索引越界报错

解决Python中用.format打印DataFrame形状的报错问题

嘿,我来帮你搞定这个问题!咱们先拆解下你代码里的问题,再给你几种靠谱的正确写法。

为什么会报错?

你的字符串模板"The data has Rows {}, Columns {}"有两个占位符{},但调用.format()的时候只传了df_shape[0]这一个参数——这直接导致参数数量不匹配,正常会报TypeError;你提到的IndexError大概率是代码里的小失误(比如不小心写了df_shape[2]这种不存在的索引,或者极端情况下你的DataFrame异常到shape元组只有一个元素,但这种情况非常少见)。

正确的写法

方法1:解包shape元组(最简洁)

df.shape本身就是一个包含行数、列数的二元组,用*运算符直接把元组拆成两个参数传给.format()就行:

df_shape = df.shape
print("The data has Rows {}, Columns {}".format(*df_shape))

方法2:分别传入行和列的数值

如果你想更明确地指定每个占位符对应的值,直接把行数和列数都传进去就好:

df_shape = df.shape
print("The data has Rows {}, Columns {}".format(df_shape[0], df_shape[1]))

方法3:用f-string(Python 3.6+推荐写法)

这是现在Python里更简洁直观的字符串格式化方式,比.format()写起来顺手多了:

# 先存变量的写法
df_shape = df.shape
print(f"The data has Rows {df_shape[0]}, Columns {df_shape[1]}")

# 省去变量,直接调用的写法
print(f"The data has Rows {df.shape[0]}, Columns {df.shape[1]}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:15