1.转换为列表的列表(每行一个子列表)
import pandas as pd # 示例DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # 方法1: 使用 values.tolist() list_of_lists = df.values.tolist() # 结果: [[1, 4, 7], [2, 5, 8], [3, 6, 9]] # 方法2: 使用 to_numpy().tolist() list_of_lists = df.to_numpy().tolist()2.转换为字典列表(每行一个字典)
# 每行作为一个字典 dict_list = df.to_dict('records') # 结果: [{'A': 1, 'B': 4, 'C': 7}, # {'A': 2, 'B': 5, 'C': 8}, # {'A': 3, 'B': 6, 'C': 9}]3.按列转换为列表
# 每列作为一个列表 column_lists = df.values.T.tolist() # 结果: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # 或者分别获取每列 col_a_list = df['A'].tolist() # [1, 2, 3] col_b_list = df['B'].tolist() # [4, 5, 6]4.转换为嵌套字典的不同格式
# 'index'格式: 索引作为外层键 dict_index = df.to_dict('index') # 结果: {0: {'A': 1, 'B': 4, 'C': 7}, # 1: {'A': 2, 'B': 5, 'C': 8}, # 2: {'A': 3, 'B': 6, 'C': 9}} # 'split'格式: 分离数据、列名和索引 split_dict = df.to_dict('split') # 结果: {'index': [0, 1, 2], # 'columns': ['A', 'B', 'C'], # 'data': [[1, 4, 7], [2, 5, 8], [3, 6, 9]]}5.保留索引信息
# 将索引也包含在列表中 df_with_index = df.reset_index() list_with_index = df_with_index.values.tolist() # 结果: [[0, 1, 4, 7], [1, 2, 5, 8], [2, 3, 6, 9]]6.处理特定数据类型
# 如果DataFrame中有复杂数据类型,建议先转换 df_clean = df.astype(str) # 先转换为字符串 str_list = df_clean.values.tolist()选择建议:
需要简单矩阵数据:用
df.values.tolist()需要保持列名信息:用
df.to_dict('records')需要按列处理:用
df['列名'].tolist()需要完整结构信息:用
df.to_dict('split')