如何在Python中将普通列表转换为固定3列的DataFrame
将一维浮点列表转换为指定结构的3列DataFrame
需求说明
给定一个长度为3的倍数的浮点元组(示例如下):
InputList = (0.5, 0.3, 0.2, 0.8, 1.2, 0.5, 0.6, 0.7, 0.9, 1.4, 1.1, 0.3)
需要将其转换为包含3列的DataFrame,最终格式如下:
Index, Col1, Col2, Col3 0, 0.5, 1.2, 0.9 1, 0.3, 0.5, 1.4 2, 0.2, 0.6, 1.1 3, 0.8, 0.7, 0.3
实现方案
可以用Python的pandas结合numpy快速实现,也可以通过纯切片拆分完成,两种方案如下:
方案1:基于numpy数组重塑(高效简洁)
import pandas as pd import numpy as np # 输入数据 InputList = (0.5, 0.3, 0.2, 0.8, 1.2, 0.5, 0.6, 0.7, 0.9, 1.4, 1.1, 0.3) # 计算每列的元素数量(总长度除以3) col_count = len(InputList) // 3 # 重塑数组结构并转置,生成DataFrame df = pd.DataFrame( np.array(InputList).reshape(3, col_count).T, columns=['Col1', 'Col2', 'Col3'] ) # 输出验证(可选) print(df.to_csv(sep='\t', index=True))
逻辑说明
- 先通过
len(InputList)//3算出每列要容纳的元素数(示例中为4); - 将一维输入转成numpy数组后,重塑为3行
col_count列的结构,每行对应最终的一列数据; - 转置数组得到
col_count行3列的结构,直接匹配目标DataFrame的格式,最后指定列名即可。
方案2:纯切片拆分(无需numpy依赖)
import pandas as pd InputList = (0.5, 0.3, 0.2, 0.8, 1.2, 0.5, 0.6, 0.7, 0.9, 1.4, 1.1, 0.3) col_count = len(InputList) // 3 # 按位置拆分出三个子列表,分别作为DataFrame的列 col1 = InputList[:col_count] col2 = InputList[col_count:2*col_count] col3 = InputList[2*col_count:] df = pd.DataFrame({'Col1': col1, 'Col2': col2, 'Col3': col3})
内容的提问来源于stack exchange,提问作者Cyril Ezhov
相关产品推荐
相关产品推荐

