如何在dataframe整数序列的元素间插入-1且保持末尾为-2
你可以直接通过pandas的apply方法对每一行序列做自定义处理,代码逻辑简单,48万行数据可以在秒级完成处理。
具体实现代码如下:
import pandas as pd # 自定义序列处理函数 def insert_separator(s): # 将空格分隔的字符串转为整数列表 num_list = list(map(int, s.split())) processed = [] for idx, num in enumerate(num_list): processed.append(num) # 不在最后一个元素后插入-1 if idx != len(num_list) - 1: processed.append(-1) # 转回空格分隔的字符串格式 return ' '.join(map(str, processed)) # 应用函数到序列列 df['sequences'] = df['sequences'].apply(insert_separator)
效果验证
拿你给出的示例输入测试:
- 原序列:
2 2 0 -2→ 处理后:2 -1 2 -1 0 -1 -2 - 原序列:
1 0 2 1 1 -2→ 处理后:1 -1 0 -1 2 -1 1 -1 1 -1 -2
完全符合需求。
如果追求更精简的写法,也可以用itertools工具类实现相同逻辑:
from itertools import chain, repeat def insert_separator(s): nums = list(map(int, s.split())) return ' '.join(map(str, chain.from_iterable(zip(nums, repeat(-1))))).rsplit(' ', 1)[0]
内容的提问来源于stack exchange,提问作者Robin van Heesch
相关产品推荐
相关产品推荐

