简体   繁体   English

熊猫循环并追加失败

[英]Pandas Loop and Append Failure

So I'm trying to send a datframe of VINs to the nhtsa open source api and get the information back. 因此,我正在尝试将datframe的VIN发送到nhtsa开源api,并获取信息。 The below works with replacing df['vin'] with an actual vin. 下面的工作将df['vin']替换为实际的vin。 However when adding the loop to my function and trying to append, the result is that I get a blank dataframe back instead of the information for the 12 or so VINs. 但是,当将循环添加到函数中并尝试追加时,结果是我得到了一个空白数据框,而不是12个左右VIN的信息。 What am I doing wrong? 我究竟做错了什么?

Code below: 代码如下:

import pandas as pd
import requests
    #develop the data
z = pd.DataFrame(columns = ["vin"], data = ['LHJLC79U58B001633','SZC84294845693987','LFGTCKPA665700387','L8YTCKPV49Y010001',
                                                 'LJ4TCBPV27Y010217','LFGTCKPM481006270','LFGTCKPM581004253','LTBPN8J00DC003107',
                                                 '1A9LPEER3FC596536','1A9LREAR5FC596814','1A9LKEER2GC596611','1A9L0EAH9C596099',
                                                 '22A000018'])

z['manufacturer'] = ['A','A','A','A','B','B','B','B','B','C','C','D','D']



def nhtsa(df):
    '''
    sends VIN to NHTSA for data call
    '''
    for i in df:
        url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/'
        post_fields = {'format': 'json', 'data': df['vin']};
        r = requests.post(url, data=post_fields);
        x = r.json()
        f = pd.DataFrame(x['Results'])
        g = f[['VIN','Make','Manufacturer','ManufacturerId','ManufacturerType', 'Model','ModelYear', 'ABS','VehicleType', 'BodyClass','DisplacementCC','ErrorCode', 'SuggestedVIN']]
        csv = pd.DataFrame()
        csv = csv.append(g, ignore_index = True)
        return csv

nhtsa(z)

Ok. 好。 So, thanks to @G.Anderson, I figured this out. 因此,感谢@ G.Anderson,我弄清楚了这一点。 First, the empty data frame should be outside of the loop. 首先,空数据帧应位于循环外部。 Next, the i, as stated by G.Anderson was not getting called out. 接下来,G.Anderson所说的i没有被召唤出来。 I used a .loc statement to call what i is. 我用.loc语句称呼i是什么。 Below is the code. 下面是代码。

def nhtsa(df):
    '''
    sends VIN to NHTSA for data call
    '''
    df1 = pd.DataFrame()
    for i in current_trial.index:
        vin = df.loc[i, 'VIN']
        url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/'
        post_fields = {'format': 'json', 'data': vin};
        r = requests.post(url, data=post_fields);
        x = r.json()
        f = pd.DataFrame(x['Results'])
        g = f[['VIN','Make','Manufacturer','ManufacturerId','ManufacturerType', 'Model','ModelYear', 'ABS','VehicleType', 'BodyClass','DisplacementCC','ErrorCode', 'SuggestedVIN']]
        df1 = df1.append(g)
    return df1  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM