当前位置: 首页 > news >正文

python如何把多维列表转换为dataframe

在 Python 中,我们可以使用 `pandas` 库将多维列表转换为 `DataFrame`。不同维度的多维列表转换为 `DataFrame` 的方式有所不同,下面分别针对二维、三维及更高维度列表给出具体的转换示例。

### 1. 二维列表转换为 `DataFrame`

二维列表是最常见的多维列表形式,可将其看作表格数据,每一行对应 `DataFrame` 中的一行,每一列对应 `DataFrame` 中的一列。

```python

import pandas as pd

# 定义二维列表
two_d_list = [
    [
1, 2, 3],
    [
4, 5, 6],
    [
7, 8, 9]
]


# 转换为 DataFrame
df = pd.DataFrame(two_d_list, columns=['col1', 'col2', 'col3'])
print('type(df): ',type(df))
print(df)

```

#### 代码解释:

- `pd.DataFrame(two_d_list)`:使用 `pandas` 的 `DataFrame` 构造函数将二维列表转换为 `DataFrame`。

- `columns=['col1', 'col2', 'col3']`:通过 `columns` 参数指定 `DataFrame` 的列名。

### 2. 三维列表转换为 `DataFrame`

三维列表转换为 `DataFrame` 时,通常需要将其进行一定的处理,比如将其展开成二维形式,以便于转换。

```python

import pandas as pd

# 定义三维列表
three_d_list = [
    [
        [
1, 2],
        [
3, 4]
    ],
    [
        [
5, 6],
        [
7, 8]
    ]
]


print('原三维列表: ',type(three_d_list))
print(three_d_list)

# 展开三维列表为二维列表
flattened_list = []
for sub_list_2d in three_d_list:
   
for sub_list_1d in sub_list_2d:
        flattened_list.append(sub_list_1d)


# 转换为 DataFrame
df = pd.DataFrame(flattened_list, columns=['col1', 'col2'])
print('转换后的dataframe: ',type(df))
print(df)

```

#### 代码解释:

- 首先,通过嵌套循环将三维列表展开为二维列表 `flattened_list`。

- 然后,使用 `DataFrame` 构造函数将展开后的二维列表转换为 `DataFrame`,并指定列名。

### 3. 更高维度列表转换为 `DataFrame`

对于更高维度的列表,同样需要先将其转换为二维形式,再进行 `DataFrame` 的转换。以下是一个四维列表转换的示例:

```python

import pandas as pd

# 定义四维列表
four_d_list = [
    [
        [
            [
1, 2],
            [
3, 4]
        ],
        [
            [
5, 6],
            [
7, 8]
        ]
    ],
    [
        [
            [
9, 10],
            [
11, 12]
        ],
        [
            [
13, 14],
            [
15, 16]
        ]
    ]
]


print('原高维列表: ',type(four_d_list))
print(four_d_list)

# 展开四维列表为二维列表
flattened_list = []
def flatten(lst):
   
for item in lst:
       
if isinstance(item, list):
            flatten(item)
       
else:
            flattened_list[-
1].append(item)

for sub_list_3d in four_d_list:
   
for sub_list_2d in sub_list_3d:
        flattened_list.append([])
        flatten(sub_list_2d)


# 转换为 DataFrame
df = pd.DataFrame(flattened_list, columns=['col1', 'col2','col3','col4'])
print('转换后的dataframe: ',type(df))
print(df)

```

#### 代码解释:

- 定义了一个递归函数 `flatten` 用于将多维列表展开。

- 通过嵌套循环和递归函数将四维列表展开为二维列表 `flattened_list`。

- 最后使用 `DataFrame` 构造函数将展开后的二维列表转换为 `DataFrame`,并指定列名。

通过以上示例可以看出,将多维列表转换为 `DataFrame` 的关键在于将其转换为合适的二维形式,以便于使用 `pandas` 的 `DataFrame` 构造函数进行转换。

注意:`DataFrame`始终是一个二维的表格,对于多维的数据转换为`DataFrame`的方法就是先把高维的数据进行分解。

相关文章:

  • 【RabbitMQ | 第1篇】Erlang 和 RabbitMQ 的下载安装
  • easyconnect下服务器联网
  • 大白话JavaScript原型链查找机制与继承实现原理
  • Service与Ingress:如何将你的应用暴露给世界
  • 嵌入式 ARM Linux 系统构成(6):应用层(Application Layer)
  • VSTO(C#)Excel开发1:起步 示例项目
  • 【从零开始学习计算机科学】计算机组成原理(二)信息表示与编码
  • Ardupilot开源无人机之Geek SDK进展2025Q1
  • 用AI学习ANN人工神经网络2——什么是Transformer
  • Element使用
  • 力扣72题编辑距离
  • 【弹性计算】异构计算云服务和 AI 加速器(三):GPU 虚拟化技术
  • nuxt2 打包优化使用“compression-webpack-plugin”插件
  • Docker常用命令清单
  • python用户图形界面wxpython库安装与使用
  • S19文件格式详解:汽车ECU软件升级中的核心镜像格式
  • 谷歌浏览器中 Google 翻译无法使用的解决办法
  • AcWing 5538. 回文游戏 博弈论
  • 从零开始学机器学习——网络应用
  • Spring Batch 概览
  • 特朗普:将于19日分别与普京和泽连斯基通话
  • 101岁陕西省军区原司令员冀廷璧逝世,曾参加百团大战
  • 新华时评:博物馆正以可亲可近替代“高冷范儿”
  • 长三角体育节回归“上海时间”,首次发布赛事旅游推荐线路
  • 霍步刚任辽宁沈阳市委书记
  • 秦洪看盘|风格有所转变,热钱回流高弹性品种