You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将单栏txt按4行分组转换为多列pandas DataFrame

实现方案

方案1:基于numpy reshape实现(简洁高效,推荐)

import pandas as pd
import numpy as np

# 替换为你的txt文件路径
single_col_data = pd.read_csv("data.txt", header=None).values
# -1会自动根据数据总长度计算行数,适配任意符合4的整数倍长度的输入
df = pd.DataFrame(single_col_data.reshape(-1, 4))

方案2:纯pandas实现(无需额外依赖numpy)

import pandas as pd

# 替换为你的txt文件路径
single_col_df = pd.read_csv("data.txt", header=None)
# 按索引每4行分组,转换为多列结构
df = pd.DataFrame(single_col_df.groupby(single_col_df.index // 4)[0].apply(list).tolist())

效果验证

以你提供的示例数据为例,两种方案最终输出的DataFrame结构均为:

0   1   2  3
0  12  21  23  1
1  23  42  12  0

完全符合前3列为特征、第4列为标签的分组规则,无自定义列名。

内容的提问来源于stack exchange,提问作者Ateeq Ur Rehman AU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:15:03