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

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

问题描述:

我有以下熊猫数据框:

   date
0   1
1   2
2   23
3   31
4   4
...
n    3

如何用以下格式替换从1到9的所有数字(例如,具有一位数字的数字):

How can I only replace all the numbers from 1 to 9 (e.g. numbers with one digit) with the following format:

01, 02, 03, 04, 05, 06, 07, 08, 09

我尝试使用以下熊猫替换功能:

I tried to do with pandas replace function the following:

df['date'] = df['date'].replace(['1', '2', '3', '4', '5', '6', '7', '8', '9']),
                                                          [' 01 ', ' 02 ', ' 03 ', '04 ', ' 05 ', ' 06 ', ' 07 ', ' 08 ', ' 09 '],regex=True)

但是,它没有作用,因为它正在修改全部(即数字多于一个的数字)数据框内的数字.因此,如何规范日期列?

However, it didn't worked because it is modifying all (i.e. numbers with more than one digit) the numbers inside the dataframe. Thus, how can I normalize the date column?.

如果需要,使用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