簡體   English   中英

使用 Pandas to_dict() 時的空字典

[英]Empty dictionary when using Pandas to_dict()

我正在嘗試使用 Pandas 從 CSV 創建 JSON 文件。 我有以下 function 但我遇到了 Incidents 字典不包含任何內容的問題。

import pandas as pd
import json

data = pd.read_csv('ufo-sightings.csv',sep = ',', delimiter = None,encoding='latin-1', dtype=str)

data_new = data.rename(columns = {
    'duration (seconds)' : 'Seconds',
    'duration (hours/min)' : 'Hours',
    'date posted' : 'DatePosted', 
    'city' : 'City', 
    'state' : 'State', 
    'country' : 'Country',
    'shape' : 'Shape', 
    'comments' : 'Comments',
    'latitude' : 'Latitude',
    'longitude ' : 'Longitude'
})

df = data_new[['City', 'State', 'Country', 'Shape', 'Seconds', 'Hours',
       'Comments', 'DatePosted', 'Latitude', 'Longitude']]

sightings = df[['Country']].drop_duplicates().sort_values(['Country'], ascending = [True])

def writeEfile(filename):

    file = open(filename,'w')
    rec = 'use UFO\n'
    file.write(rec)
    
    for r in thisfile[['Country']].itertuples(index = False):
        theserows = (df[(df['Country']==r)])
        print(type(r))
        print(type(theserows))
        
        agginfo = theserows[['State', 'City', 'Shape', 'Seconds', 'Hours', 'Comments', 'DatePosted', 'Latitude', 'Longitude']]

        entries = json.dumps({"Country" : r,
                              "Incidents": agginfo.to_dict('records')})
        
        rec = 'db.ufo_sightings.insert(' + entries + ')\n'
        file.write(rec)
    file.close()
    return()

filename = 'ufo_sightings.js'
thisfile = sightings
b = writeEfile(filename)

為糟糕的變量名和過度使用道歉。

我的目標是創建一個具有以下結構的 JSON 文件 - db.ufo_sightings.insert({"Country": "us", "Incidents": [{"City": "New York City", "State": "New York"}, {"City": "LA", "State": "California"}... ]})如果城市與目擊中的城市 dataframe 匹配,則您將該事件放在正確的國家/地區。

在該方法中,您使用的這個文件等同於thisfile sightings 由於這條線, sightings object 只有 Country 列

sightings = df[['Country']].drop_duplicates().sort_values(['Country'], ascending = [True])

在循環中,(可以簡化為for idx, row in thisfile.iterrows() )您正在訪問其他不存在的列。 因此由於行agginfo.to_dict()為空字典

如果您的目標是刪除 df 中的重復項並按國家/地區排序,您可以簡單地執行

sightings = df.drop_duplicates(subset=['Country']).sort_values('Country', ascending=True)

進一步編輯,因為您需要更多幫助。

因此,對於初學者來說,刪除重復項是一個壞主意,因為您需要具有相同國家名稱的所有其他列值。

所以這里是一個 function 我會定義:

def create_json(df):
    for country in df["Country"].unique():
        allrows = df.loc[df["Country"] == country, ]
        incidents = []

        for _, row in allrows.iterrows():
            incidents.append({
                "City": str(row['City'])),
                "State": str(row['State'])),
                ### Similarly add all the other required fields.
            })

        print(json.dumps({
              "Country": str(country),
              "Incidents": incidents
            })
        )

然后對數據調用 function 而不刪除重復項,所以:

create_json(df)

這將打印所有 json 轉儲。 只需將其分配給一些 object 並執行進一步的 function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM