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

Pandas中apply调用pad函数报错,zfill正常的问题咨询

问题解答

原因分析

  • zfill是Python**原生字符串(str)**的内置方法,当你用apply(lambda x: x.zfill(10))时,x是DataFrame列中的单个字符串对象,直接调用原生方法自然可行。
  • pad是pandas的Series.str专属方法,它是针对整个Series的向量化操作接口,不能直接调用在单个字符串对象上,这就是报错AttributeError: 'str' object has no attribute 'pad'的根本原因。

实现方案

有两种可靠的解决方式:

方式一:使用Python原生字符串方法替代

Python原生字符串提供了rjust/ljust/center方法,对应pad的不同填充方向:

  • 左填充(side="left"):用rjust(右对齐,左侧补填充字符)
  • 右填充(side="right"):用ljust(左对齐,右侧补填充字符)
  • 两侧填充(side="both"):用center

修改后的代码:

print(df["Date"].apply(lambda x: x.rjust(10, '0')))

方式二:直接使用pandas的str.pad向量化操作(推荐)

既然pad是Series.str的方法,直接对Series调用即可,无需apply,效率更高:

print(df["Date"].str.pad(10, side="left", fillchar="0"))

完整测试代码

import pandas as pd
from io import StringIO

StringData = StringIO(
    """Date,Time
パンダ,パンダ
パンダサンDA12-3,パンダーサンDA12-3
パンダサンDA12-3,パンダサンDA12-3
    """
)

df = pd.read_csv(StringData, sep=",")

# 原生方法实现
print(df["Date"].apply(lambda x: x.rjust(10, '0')))
# pandas向量化实现
print(df["Date"].str.pad(10, side="left", fillchar="0"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:40:30