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

Python中如何将列表转换为DataFrame并指定列名?

问题描述

我有一个列表形式的数据,希望将其转换为每行对应一组数据的DataFrame,并为各列指定列名。给出的列表为:

[['Lato', 85, 4, 12.0, 0.04633125, 160000, 0, 0, 0, 16, 15, 17]]

当前尝试转换后得到空DataFrame,列显示为嵌套列表:

Empty DataFrame
Columns: [[['Lato', 85, 4, 12.0, 0.04633125, 160000, 0, 0, 0, 16, 15, 17]]]
Index: []

期望得到指定列名的DataFrame:

font_label| font_size|len_words|letter_per_words|text_area_ratio|image_area|flag_present|detect_face_col| detect_logos |r |g |b
Lato      |     85   |    4    |      12.0      |  0.04633125   | 160000   |       0    |      0        |     0        |16|15|17|

我尝试了以下代码:

df1_update1 = str(df1.columns[0][3:])
df1_update2 = df1_update1.replace("]","").replace("[","")

但不知道后续如何操作,恳请帮助。

解决方案

直接从原始列表构造DataFrame是最直接的正确方式,不需要处理错误生成的空DataFrame:

  • 先定义列名列表:
columns = [
    'font_label', 'font_size', 'len_words', 'letter_per_words',
    'text_area_ratio', 'image_area', 'flag_present', 'detect_face_col',
    'detect_logos', 'r', 'g', 'b'
]
  • 用原始数据创建DataFrame:
import pandas as pd

data = [['Lato', 85, 4, 12.0, 0.04633125, 160000, 0, 0, 0, 16, 15, 17]]
df = pd.DataFrame(data, columns=columns)

如果已经生成了那个错误的df1,可以这样修复:

# 从错误的列中提取原始数据
raw_data = df1.columns[0][0]
# 构造正确的DataFrame
df_fixed = pd.DataFrame([raw_data], columns=columns)

内容的提问来源于stack exchange,提问作者Sasi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:50:29