【问题标题】:How to remove a key from dict and specific column?如何从字典和特定列中删除键?
【发布时间】:2016-05-10 06:34:33
【问题描述】:

请这是我的代码。我想从输出中删除键,只有“值”和更多,因为我按“日期”分组,我不希望该列显示在列表中。 谢谢

df = pd.read_csv('testdata.csv')
json_dict = {}
for date_range, flights in df.groupby('date'):
    json_dict[date_range]= [str(v) for v in flights.to_dict(orient='records')]

with open('testdata.json', 'w') as f:
     json.dump(json_dict, f, indent=4, sort_keys=True)

当前输出:

{
    "2001-04-10--2001-02-02": [
        "{'Date': '2001-04-10--2001-02-02', 'DptCity_DptCountry': 'Beijing_Japan', 'AuthorID': 'GGG', 'ArCity_ArCountry': 'Paris_France'}"
    ], 
    "2008-03-10--2001-02-02": [
        "{'Date': '2008-03-10--2001-02-02', 'DptCity_DptCountry': 'London_UK', 'AuthorID': 'BBB', 'ArCity_ArCountry': 'Lagos_Nigeria'}", 
        "{'Date': '2008-03-10--2001-02-02', 'DptCity_DptCountry': 'NewYork_US', 'AuthorID': 'DDD', 'ArCity_ArCountry': 'Nairobi_Kenya'}", 
        "{'Date': '2008-03-10--2001-02-02', 'DptCity_DptCountry': 'London_UK', 'AuthorID': 'EEE', 'ArCity_ArCountry': 'Paris_France'}", 
        "{'Date': '2008-03-10--2001-02-02', 'DptCity_DptCountry': 'NewYork_US', 'AuthorID': 'FFF', 'ArCity_ArCountry': 'Paris_France'}"
    ], 
    "2008-03-10--2001-04-02": [
        "{'Date': '2008-03-10--2001-04-02', 'DptCity_DptCountry': 'Beijing_Japan', 'AuthorID': 'CCC', 'ArCity_ArCountry': 'Paris_France'}"
    ], 
    "2008-03-12--2001-02-02": [
        "{'Date': '2008-03-12--2001-02-02', 'DptCity_DptCountry': 'NewYork_US', 'AuthorID': 'AAA', 'ArCity_ArCountry': 'Paris_France'}"
    ]
}

期望的输出:

{
    "2001-04-10--2001-02-02": [
        "{'Beijing_Japan','GGG',  'Paris_France'}"
    ], 
    "2008-03-10--2001-02-02": [
        "{'London_UK', 'BBB','Lagos_Nigeria'}", 
        "{'NewYork_US','DDD','Nairobi_Kenya'}", 
        "{'London_UK','EEE','Paris_France'}", 
        "{'NewYork_US','FFF', 'ArCity_ArCountry': 'Paris_France'}"
    ], 
    "2008-03-10--2001-04-02": [
        "{'Beijing_Japan','CCC','Paris_France'}"
    ], 
    "2008-03-12--2001-02-02": [
        "{'NewYork_US','AAA','Paris_France'}"
    ]
}

【问题讨论】:

    标签: python json dictionary pandas dataframe


    【解决方案1】:

    试试:

    for date_range, flights in df.groupby('date'):
        flights_no_date = flights.drop('date', axis=1)
        json_dict[date_range]= map(list, flights_no_date.values)
    

    【讨论】:

    • 谢谢先生,请问我如何从列表中删除日期,因为我已经有了它 [date_range],我不希望它在航班上。谢谢
    • 您可以在 .groupby() 之前使用 df.drop('date', axis=1),因为您似乎根本不需要 column
    • 我只需要它来分组,并显示在它是所需的输出而不是在正文中
    • 这是它带来的错误:请参阅文档中的警告:pandas.pydata.org/pandas-docs/stable/…
    • 这只是一个警告,您可以尝试不使用inplace=True,查看更新。
    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2022-11-01
    • 2021-07-07
    相关资源
    最近更新 更多