【问题标题】:How can I manipulate JSON file in python to make first column the first row?如何在 python 中操作 JSON 文件以使第一列成为第一行?
【发布时间】:2022-01-05 10:37:46
【问题描述】:

我正在尝试下载此测试 json 文件以在分类项目中使用它。我已使用此代码将此 JSON 文件转换为 pandas 中的 csv 文件:

test_sarcasm_df = pd.read_json('/content/drive/My Drive/Sarcasm Data/test_sarcasm.json')

我在 ML 项目中使用它,但格式错误。我不熟悉 JSON 及其 大文件,那么有什么办法可以格式化它,使第一列成为数据框中的第一行?

感谢你们能给我的任何帮助!

数据框如下所示:

【问题讨论】:

  • 你是说你需要转置行和列吗?如果是这样,这可能会有所帮助pandas.pydata.org/docs/reference/api/…
  • @bguest 谢谢!我认为这将处理列,但我忘记了数据?如何移动值以便它们也出现在右列下?例如,Fishburn 属于作者。
  • 如果您以可重复使用的格式为其他人发布您的数据并包含您想要的输出的具体细节,这将容易得多。您可以在 How to make good, reproducible pandas examples 上查看这篇 Stack Overflow 帖子

标签: python json pandas csv


【解决方案1】:

Pandas transpose 正好解决了这个问题:

from pandas import DataFrame


df = DataFrame([{"row1": "text2", "row2": "text1"},{"row1": "bob", "row2": "james"}])
df.index = ["text", "author"]
print(df.head(2))
# this is essentially the starting position
         row1   row2
text    text2  text1
author    bob  james



# now we transpose
df = df.transpose()
print(df.head(2))

# problem solved :)
       text author
row1  text2    bob
row2  text1  james

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 2021-08-18
    • 1970-01-01
    • 2020-07-07
    • 2013-08-01
    • 2022-01-03
    • 2016-08-05
    • 2018-11-20
    • 2015-01-09
    相关资源
    最近更新 更多