且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 pandas 数据框中仅将单个数字替换为另一个数字?

更新时间:2023-02-09 23:27:03

如果需要,使用astype(str)将列强制转换为str,然后调用

If needed cast the column to str using astype(str), then call str.zfill to 0 pad those numbers:

In [13]:
df['date'] = df['date'].astype(str).str.zfill(2)
df

Out[13]:
  date
0   01
1   02
2   23
3   31
4   04

关于您的评论:

In [17]:
df['year'] = '20' + df['date']
df

Out[17]:
  date  year
0   01  2001
1   02  2002
2   23  2023
3   31  2031
4   04  2004

当列dtype已经是str

the above works when the column dtype is already str