【问题标题】:How to add columns and delete columns in a Json file then save it into csv如何在 Json 文件中添加列和删除列,然后将其保存到 csv
【发布时间】:2021-11-11 13:21:01
【问题描述】:

我尝试使用数据框将列和值添加到 json 文件中,但似乎在我尝试删除某些列之后它返回到原始数据文件。我还遇到了无法将其保存到 csv 文件中的问题。所以想知道也许我不能为此使用数据框?

它就像一个列表,分为不同的列(总共大约 30 行),但是我想删除一些像路由和 urls,同时添加长度、maxcal、mincal 的三列(这些中的所有值在路线列中找到 3 列)

到目前为止,我已经这样做了,但被卡住了:

import pandas as pd
import json

data = pd.read_json('fitness.json') # fitness.json is the filename of the json file

fitness2 = pd.DataFrame (fitness2)
fitness2

data.join(fitness2, lsuffix="_left") # to join the three columns into the data table 


我不确定如何删除路线列、“MapURL”、“MapURL_tc”、“MapURL_sc”,然后最终保存为 csv,如显示的输出。

谢谢。

【问题讨论】:

    标签: python json dataframe csv multiple-columns


    【解决方案1】:

    您可以删除列,然后连接两个数据框:

    data.drop(['MapURL', 'MapURL_tc', 'MapURL_sc'], inplace=True, axis=1)
    
    pd.concat([data,fitness2], axis=1) # to join the three columns into the data table
    

    【讨论】:

    • 您好,感谢您的回复。是的,我这样做了,但是如果我使用 data.join(fitness2, lsuffix="_left") 添加列,它将打印出我的原始 txt 文件。而且我不确定如何将新编辑的内容保存在 csv 中,在数据框中似乎无法保存到 csv
    • 能否将 Fitness.json 作为文本发布在帖子上,以便我测试代码?
    • 当然,已经发布了。
    • 看看现在能不能用
    猜你喜欢
    • 2017-03-01
    • 2021-06-29
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多