如何用Python Pandas移动指定列并在原位置留空列?
我正在学习Python,编写读取多列XLSX文件的脚本,需要将当前M-W列(对应“rndm_tags”相关列,原位置从N列开始)移动到X列开始的位置,原位置留空列。
当前使用的代码
#Currently in use #read excel file clean = pd.read_excel('test2.xlsx', header=None) print("Column headings:") print(clean.columns) #top = list(clean.columns.values) #print(top) #remove duplicates dedup = clean.drop_duplicates() dedup.insert(25, "", [""]) #dedup.to_excel('test3.xlsx', index=False, header=False, columns=[1,2,3,4,5,6,7,8,9,10,11,12,13,24,25,26,27,28,29,30,31,32,33,13,14,15,16,17,18,19,20,21,22,23]) print("Column headings:") print(dedup.columns) #End of currently in use
执行错误信息
Column headings:
Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24],
dtype='int64')
Traceback (most recent call last):
File "", line 264, in
dedup.insert(25, "", [""])
File "frame.py", line 4438, in insert
value = self._sanitize_column(value)
File "", in _sanitize_column
com.require_length_match(value, self.index)
File "common.py", line 557, in require_length_match
raise ValueError(
ValueError: Length of values (1) does not match length of index (667)
尝试过的其他代码
#Begin Other Attempts Testing Rearranging columns # adCol = rd.reindex(columns = rd.columns.tolist() + ["23","24","25","26","27","28","29","30","31","32"]) # rd.columns(adCol) # rd.to_excel('test4.xlsx', header=None, index=False) # print("Column headings:") # print(rd.columns)
解决方案
1. 先解决插入空列的错误
你遇到的ValueError是因为insert方法传入的value长度(1)和DataFrame的行数(667)不匹配。插入空列时,需要生成和行数一致的空值列表:
# 替换原来的insert代码 dedup.insert(25, "", [""] * len(dedup))
2. 完整实现列移动+原位置留空的逻辑
以下是满足需求的完整代码,核心思路是:先在目标位置插入对应数量的空列,再将原列数据复制到新位置,最后清空原列数据:
import pandas as pd # 读取文件并去重 clean = pd.read_excel('test2.xlsx', header=None) dedup = clean.drop_duplicates() # --- 请根据实际列位置调整以下参数 --- # 要移动的列范围:M-W列(对应0索引12到22,共11列) cols_to_move = dedup.columns[12:23] # 目标起始位置:X列(对应0索引23) target_start = 23 # --- 参数调整结束 --- # 步骤1:在目标位置插入与要移动列数相同的空列 for i in range(len(cols_to_move)): dedup.insert(target_start + i, f"temp_empty_{i}", [""] * len(dedup)) # 步骤2:将原列数据复制到新插入的空列中 for idx, col in enumerate(cols_to_move): dedup.iloc[:, target_start + idx] = dedup[col].values # 步骤3:清空原位置的列数据 dedup[cols_to_move] = "" # 保存结果(可根据需要调整参数) dedup.to_excel('test3.xlsx', index=False, header=False)
关键说明
- 请根据你的Excel实际列位置调整
cols_to_move和target_start的索引值(注意Pandas是0起始索引) - 插入空列时用
[""] * len(dedup)保证长度匹配,避免报错 - 通过复制+清空的方式实现“移动后原位置留空”的需求,而不是直接重排列(重排列无法保留原空列位置)
内容的提问来源于stack exchange,提问作者user19725938

