python - 将小于 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()
我意识到如何将列中的值大写,但不确定如何添加两位数的位置。任何建议表示赞赏。
解决方案
尝试使用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
然后应用于upper
列0
,并应用于zfill
列1
。
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
推荐阅读
- php - 计算数组结果差异
- python - Django 规则重用谓词
- java - Selenium 卡在 WebDriver 对象上
- android - Android ProGuard: Getting an error of 'Use of generics not allowed for java type at '<1>_<2>_<3>JsonAdapter' in line 43 of file ...'
- postgresql - 迁移后错误,我有两列,为什么?
- python - Python,代码做第一件事然后循环到最后
- python - 如何使用 predict_generator 和 generate_arrays_for_predict 可视化 ROC 曲线?
- css - Marp-CLI:如何使用导入默认主题的自定义主题
- video-streaming - 如何避免在网站上下载 mp4 视频?
- linux - 无法从主机操作系统或从容器到主机操作系统的网络访问 docker 容器