如何用Python 3将Excel单列数据重塑为每列10行的多列并导出新Excel文件
让我们一步步解决你的问题,顺便修正代码里的错误~
首先,你遇到的TypeError是因为调用reshape的方式错了:你写了newArr = arr.reshape(arr, (10, -1)),但正确的用法要么是arr.reshape(shape),要么是np.reshape(arr, shape),你把两种写法混在一起,多传了一个arr参数,所以才触发了错误。
下面给你两种完整的可行方案,覆盖「数据行数是10的倍数」和「不是10的倍数」两种场景:
方案一:修正原思路(结合NumPy)
这个方案延续你原来的想法,调整reshape的用法,同时增加异常处理应对数据行数不规整的情况:
import pandas as pd import numpy as np # 1. 导入Excel文件 df = pd.read_excel('sample.xlsx') # 2. 提取第一列并转为一维NumPy数组(比二维数组更适合reshape) first_column = df.iloc[:, 0].values # 3. 重塑为每列10行的结构 try: # 先按每行10个元素重塑,再转置得到每列10行 reshaped_arr = first_column.reshape(-1, 10).T except ValueError: # 如果数据总数不是10的倍数,自动填充NaN到最近的10的倍数 padding_count = (10 - len(first_column) % 10) % 10 padded_arr = np.pad(first_column, (0, padding_count), mode='constant', constant_values=np.nan) reshaped_arr = padded_arr.reshape(-1, 10).T # 4. 转为DataFrame并写入新Excel result_df = pd.DataFrame(reshaped_arr) result_df.to_excel('output.xlsx', index=False, header=False)
方案二:纯Pandas实现(无需NumPy)
如果你更习惯用Pandas的API,也可以用分组拼接的方式完成:
import pandas as pd import numpy as np df = pd.read_excel('sample.xlsx') first_col = df.iloc[:, 0].reset_index(drop=True) # 重置索引保证连续性 # 每10个元素为一组,拆分成多个Series column_groups = [first_col[i:i+10] for i in range(0, len(first_col), 10)] # 处理最后一组不足10个的情况,填充NaN补全 if len(column_groups[-1]) < 10: fill_values = pd.Series([np.nan] * (10 - len(column_groups[-1]))) column_groups[-1] = pd.concat([column_groups[-1], fill_values], ignore_index=True) # 将所有分组按列拼接成最终的DataFrame result_df = pd.concat(column_groups, axis=1) result_df.to_excel('output_pandas.xlsx', index=False, header=False)
小提示:
- 确保
sample.xlsx和你的脚本在同一个文件夹下,或者填写文件的完整路径(比如C:/data/sample.xlsx) - 如果不需要填充NaN,可以去掉异常处理或补全NaN的代码,但要保证数据总行数是10的倍数,否则reshape会报错
内容的提问来源于stack exchange,提问作者Sahar
相关产品推荐
相关产品推荐

