Pandas 数据处理:将字符串按指定规则分隔并连接
import pandas as pd
def format_string(s): '将字符串按照要求格式化' s = s.split('-') new_s = [] for i in range(len(s)): if len(s[i]) < 4: # 不足四位的数字前面补0 s[i] = s[i].zfill(4) if i > 0 and s[i][:2] != s[i-1][:2]: # 相邻两元素前两位不一致时用/连接 new_s.append('/') new_s.append(s[i]) return '-'.join(new_s)
df = pd.DataFrame({'A': ['1081-1091-1001-0483-0421', '611-613-639-839-837-833', '23-611-613-639', '23-611-613-639-993', '483-421'], 't': [1, 1, 1, 2, 0]})
df['B'] = df['A'].apply(format_string) print(df['B'])
原文地址: https://www.cveoy.top/t/topic/n3TS 著作权归作者所有。请勿转载和采集!