python - 我想将数据框转换为列表列表,其中包含第一个列表中的列名和其他列表中的数据

标签 python pandas dataframe

我想把这个Dataframe转换成list of list

Year  Sales  Expenses  Profit
2014  1000   400       200
2015  1170   460       250
2016  660    1120      300
2017  1030   540       350

这是预期的输出

[
    ['Year', 'Sales', 'Expenses', 'Profit'],
    ['2014', 1000, 400, 200],
    ['2015', 1170, 460, 250],
    ['2016', 660, 1120, 300],
    ['2017', 1030, 540, 350]
]

最佳答案

尝试使用:

print([df.columns.tolist()] + df.values.tolist())

输出:

[['Year', 'Sales', 'Expenses', 'Profit'], [2014, 1000, 400, 200], [2015, 1170, 460, 250], [2016, 660, 1120, 300], [2017, 1030, 540, 350]]

关于python - 我想将数据框转换为列表列表,其中包含第一个列表中的列名和其他列表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705359/

相关文章:

python - 了解 maxmin 函数

python - 脚本在 CMD 中运行时因 AttributeError 而失败,但在 IDLE 中执行正常

python - Pandas 数据转换

Python:Pandas:滚动窗口 - mean() 有效但 variance() 无效?

python - Pandas 用 nan 计算 2 列的不同组合

python - 为什么我无法安装 pyenv?

python - 通过 GroupBy 操作高效创建列

Python Pandas 每组的组中值与组总数的比率

python - 如何按 Pandas 中的时间戳排序?

python - 如何拆分句子,只让 ascii 字符