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

Python操作JSON生成pandas DataFrame时如何将首列转为首行

解决方法
  • 读取后直接调整(适用于已经将数据读入内存的场景,操作效率高,适合大体积DataFrame)
    如果需要将首列内容设置为表头:
# 提取首列值作为新列名
test_sarcasm_df.columns = test_sarcasm_df.iloc[:, 0]
# 删除冗余的首列
test_sarcasm_df = test_sarcasm_df.drop(test_sarcasm_df.columns[0], axis=1).reset_index(drop=True)

如果需要将首列整体转为第一行(列转行):

# 直接转置DataFrame即可完成列行转换
test_sarcasm_df = test_sarcasm_df.T.reset_index(drop=True)
  • 读取时直接适配JSON格式(更省内存,推荐大文件使用)
    出现格式问题大多是因为JSON存储结构和pandas默认读取规则不匹配,你可以在read_json方法中添加orient参数适配你的JSON结构,常用参数值如下:
    • orient='records':适配按行存储单条数据的JSON结构
    • orient='index':适配外层键为行索引的JSON结构
    • orient='columns':适配外层键为列名的JSON结构
      读取超大文件时可额外添加lines=True、chunksize=10000参数按批次读取,避免内存溢出。

内容的提问来源于stack exchange,提问作者Qi'ra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:54:07