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

如何解析每行含字典结构的DataFrame为常规表格格式?

解析DataFrame并生成对齐格式输出

解决方案代码

假设你的DataFrame已经是结构化(即duration、spot_per_kwh等都是独立列),可以用以下代码生成你要的点分隔对齐格式:

import pandas as pd

# 示例DataFrame(替换成你的实际数据)
data = [
    {'duration': 30.0, 'spot_per_kwh': -4.86251, 'per_kwh': 17.62777, 
     'date': pd.to_datetime('2022-10-31').date(), 
     'nem_time': pd.to_datetime('2022-10-31 00:30+10:00'), 
     'start_time': pd.to_datetime('2022-10-30 14:00:01+00:00'), 
     'end_time': pd.to_datetime('2022-10-30 14:30:00+00:00'), 
     'renewables': 111.078, 
     'channel_type': 'general', 
     'spike_status': 'none', 
     'descriptor': 'extremelyLow', 
     'type': 'ActualInterval'}
]
df = pd.DataFrame(data)

# 1. 选择需要展示的列(可根据需求调整)
columns_to_show = ['duration', 'spot_per_kwh', 'per_kwh', 'date', 'renewables']

# 2. 计算每个列的最大宽度:取列名长度和该列所有值转字符串后的最大长度的较大值
col_widths = {}
for col in columns_to_show:
    # 处理枚举/特殊类型,先转成字符串
    str_values = df[col].astype(str).tolist()
    max_val_len = max(len(s) for s in str_values)
    col_widths[col] = max(len(col), max_val_len)

# 3. 生成表头行:每个列名用点填充到对应宽度,最后拼接
header = '.....'.join([col.ljust(col_widths[col], '.') for col in columns_to_show])
print(header)

# 4. 生成每行数据:每个值转字符串后用点填充到对应宽度,拼接后打印
for _, row in df.iterrows():
    row_strs = []
    for col in columns_to_show:
        val_str = str(row[col])
        row_strs.append(val_str.ljust(col_widths[col], '.'))
    print('.....'.join(row_strs))

代码说明

  • 列选择:columns_to_show可以自定义你需要展示的字段,按需增减即可。
  • 宽度计算:自动适配每个列名和值的最长长度,保证对齐效果。
  • 特殊类型处理:把datetime、枚举类等非字符串类型转成字符串,避免格式报错。
  • 对齐填充:用ljust方法把字符串左对齐,剩余位置用.填充,再用.....分隔不同列。

如果你的原始DataFrame是每行存储一个字典(即只有一列,比如列名是data,每行是字典),需要先把字典列展开成结构化DataFrame,再执行上面的步骤:

# 展开字典列为结构化DataFrame
df = pd.json_normalize(df['data'])
# 之后执行上面的代码即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:25:28