我用这种格式获取数据..

ListA =
[
    [('test1', 'aaa', 'A'),('test2', 'bbb', 'B'),('test3', 'ccc', 'C')],
    [('test4', 'ddd', 'D'),('test5', 'eee', 'E'),('test6', 'fff', 'F')],
    [('test7', 'ggg', 'A'),('test8', 'hhh', 'B'),('test9', 'ppp', 'C')]
]

我想转换成这种格式

ID, ColA, ColB, ColC,
1, 'test1', 'aaa', 'A'
1, 'test2', 'bbb', 'B'
1, 'test3', 'ccc', 'C'
2, 'test4', 'ddd', 'D'
2, 'test5', 'eee', 'E'
2, 'test6', 'fff', 'F'
3, 'test7', 'ggg', 'A'
3, 'test8', 'hhh', 'B'
3, 'test9', 'ppp', 'C'

推荐答案

你可以使用itertools.chain:

from itertools import chain
df = pd.DataFrame(chain.from_iterable(ListA),
                  columns=['ColA', 'ColB', 'ColC'])

输出:

    ColA ColB ColC
0  test1  aaa    A
1  test2  bbb    B
2  test3  ccc    C
3  test4  ddd    D
4  test5  eee    E
5  test6  fff    F
6  test7  ggg    A
7  test8  hhh    B
8  test9  ppp    C

使用索引(可以处理不均匀的列表长度):

from itertools import chain
import numpy as np

idx = np.repeat(np.arange(len(ListA))+1, list(map(len, ListA)))

df = pd.DataFrame(chain.from_iterable(ListA),
                  columns=['ColA', 'ColB', 'ColC'],
                  index=idx).rename_axis('ID')

输出:

     ColA ColB ColC
ID                 
1   test1  aaa    A
1   test2  bbb    B
1   test3  ccc    C
2   test4  ddd    D
2   test5  eee    E
2   test6  fff    F
3   test7  ggg    A
3   test8  hhh    B
3   test9  ppp    C

Python-3.x相关问答推荐

如何在Python Matplotlib中在x轴上放置点

错误2没有这样的文件或目录website_content.txt""

Pandas 中每行的最大值范围

S的两极是什么,相当于大Pandas 的`.ilo‘方法?

如果行在所有上级索引中都为0,如何删除下级索引行?

如何在当前测试中使用fixture 转换后的数据进行参数化?

Select 作为 MultiIndex 一部分的两个 DatetimeIndex 之间的行

如何通过 python 使用 auth no priv 获取 SNMPv3?

如何将 OLS 趋势线添加到使用 updatemenus 显示数据子集的 plotly 散点图图形对象?

将数据框中的值与另一个数据框中的多列进行比较,以获取条目以有效方式匹配的列表列表

!date 的命令无法从 jupyter notebook 运行

python2和python3中的列表生成器

为什么 Sympy 不能解决我的非线性系统? Python 解释器一直在执行,直到我终止进程

如何在python中将列表转换为其他格式

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

Tkinter 窗口显示(无响应)但代码正在运行

Python:遍历子列表

如何找出从哪个模块导入名称?

如何在 FastAPI 中的一条路由上捕获任意路径?

如何从Pandas 中的字符串中提取前8个字符