如何对Pandas DataFrame的gen列按A/B值对排序并格式化?
Pandas DataFrame 格式转换实现
原始数据定义
import pandas as pd df1 = pd.DataFrame( {'st': {0: 1, 1: 0, 2: 2, 3: 0, 4: 1, 5: 5, 6: 0, 7: 7, 8: 19, 9: 0, 10: 0, 11: 0, 12: 3, 13: 0}, 'gen': {0: 'B1', 1: 'A0,B0', 2: 'A1,B1', 3: 'A0,B0', 4: 'B109', 5: 'B4,A1', 6: 'A0,B0', 7: 'A4,B3', 8: 'B15,A4', 9: 'A0,B0', 10: 'A0,B0', 11: 'A0,B0', 12: 'A123', 13: 'A0,B0'}, 'gen2': {0: 'B(1)', 1: 'A(0),B(0)', 2: 'A(1),B(1)', 3: 'A(0),B(0)', 4: 'B(109)', 5: 'A(1),B(4)', 6: 'A(0),B(0)', 7: 'A(4),B(3)', 8: 'A(4),B(15)', 9: 'A(0),B(0)', 10: 'A(0),B(0)', 11: 'A(0),B(0)', 12: 'A(123)', 13: 'A(0),B(0)'}} )
期望输出
st gen gen2 0 1 B1 B(1) 1 0 A0,B0 A(0),B(0) 2 2 A1,B1 A(1),B(1) 3 0 A0,B0 A(0),B(0) 4 1 B109 B(109) 5 5 B4,A1 A(1),B(4) 6 0 A0,B0 A(0),B(0) 7 7 A4,B3 A(4),B(3) 8 19 B15,A4 A(4),B(15) 9 0 A0,B0 A(0),B(0) 10 0 A0,B0 A(0),B(0) 11 0 A0,B0 A(0),B(0) 12 3 A123 A(123) 13 0 A0,B0 A(0),B(0)
需求说明
- 对
gen列中逗号分隔的元素排序:确保以A开头的元素排在以B开头的元素之前; - 格式化每个元素:将元素中的数字部分放入括号,最终生成
gen2列的样式(示例:B4,A1转为A(1),B(4),B15,A4转为A(4),B(15))。
实现代码
import re def process_gen(s): # 拆分逗号分隔的元素 parts = s.split(',') # 按首字母排序,A在前B在后 sorted_parts = sorted(parts, key=lambda x: x[0]) # 格式化每个元素:字母+括号包裹数字 formatted_parts = [] for part in sorted_parts: match_result = re.match(r'([AB])(\d+)', part) if match_result: letter, num_str = match_result.groups() formatted_parts.append(f"{letter}({num_str})") return ','.join(formatted_parts) # 应用函数到gen列,生成gen2 df1['gen2'] = df1['gen'].apply(process_gen) # 查看结果 print(df1)
内容的提问来源于stack exchange,提问作者josepmaria
相关产品推荐
相关产品推荐

