首页 > 解决方案 > 将小于 2 位的数值的前导零添加到现有数据框列(python)

问题描述

我有一个数据框 df,我想将所有字符串从小写转换为大写,并为小于 2 位的数值添加前导零。

数据

type    count
d       bu1
d       gpa1
d       da1
nd      da2
nd      lapp1

想要的

type    count
d       BU01
d       GPA01
d       DA01
nd      DA02
nd      LAPP01

正在做

df['count'] = df['count'].str.upper()

我意识到如何将列中的值大写,但不确定如何添加两位数的位置。任何建议表示赞赏。

标签: pythonpandas

解决方案


尝试使用str.extract+ str.upper+ str.zfill

s_df = df['count'].str.extract(r'(.*)(\d+)$')
df['count'] = s_df[0].str.upper() + s_df[1].str.zfill(2)
  type   count
0    d    BU01
1    d   GPA01
2    d    DA01
3   nd    DA02
4   nd  LAPP01

解释:

提取所有内容,直到结束数字:

s_df = df['count'].str.extract(r'(.*)(\d+)$')

将值分成 2 列

      0  1
0    bu  1
1   gpa  1
2    da  1
3    da  2
4  lapp  1

然后应用于upper0,并应用于zfill1

s_df[0].str.upper()
0      BU
1     GPA
2      DA
3      DA
4    LAPP
Name: 0, dtype: object
s_df[1].str.zfill(2)
0    01
1    01
2    01
3    02
4    01
Name: 1, dtype: object

然后连接在一起+

s_df[0].str.upper() + s_df[1].str.zfill(2)
0      BU01
1     GPA01
2      DA01
3      DA02
4    LAPP01
dtype: object

使用的数据框:

df = pd.DataFrame({'type': ['d', 'd', 'd', 'nd', 'nd'],
                   'count': ['bu1', 'gpa1', 'da1', 'da2', 'lapp1']})
  type  count
0    d    bu1
1    d   gpa1
2    d    da1
3   nd    da2
4   nd  lapp1

推荐阅读