df = pdDataFrameA 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需求是:需要把A列数据转化要求按-切分后的每个元素都保持四位相邻两元素前两位一致则用-连接不一致则用连接。存到原数据的B列中
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/fbaS 著作权归作者所有。请勿转载和采集!