猿问

在python中返回多个值并将它们附加到数据帧的唯一列

背景:


我有一个从数据库中获取一堆属性的函数。这是函数:


def getData(key, full_name, address, city, state, zipcode):

    try:

        url = 'https://personator.melissadata.net/v3/WEB/ContactVerify/doContactVerify'

        payload={

                'TransmissionReference': "test", # used by you to keep track of reference

                'Actions': 'Check',

                'Columns': 'Gender','DateOfBirth','DateOfDeath','EthnicCode','EthnicGroup','Education','PoliticalParty','MaritalStatus','HouseholdSize','ChildrenAgeRange','PresenceOfChildren','PresenceOfSenior','LengthOfResidence','OwnRent','CreditCardUser','Occupation','HouseholdIncome',

                'CustomerID': key,# key

                'Records': [{'FullName': str(full_name), 'AddressLine1': str(address), 'City': str(city), 'State': str(state), 'PostalCode': str(zipcode)}]

                }

        headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept':'application/json', 'Host':'personator.melissadata.net','Expect': '100-continue', 'Connection':'Keep-Alive'}

        r = requests.post(url, data=json.dumps(payload), headers=headers)


为了制作“性别”列,我将函数包装成一个 lambda


df['Gender'] = df.apply(lambda row: getData(key, row['Full Name'], row['Address'], row['City'], row['State'], row['Zipcode']))

目标: 我想对您在 Gender 下方看到的所有其他属性同时执行此过程,我如何在 Python 中执行此操作。


隔江千里
浏览 202回答 1
1回答

心有法竹

你可以返回一个字典,然后展开一系列字典对象:fields = ['Gender', 'DateOfBirth', etc.]def getData(key, full_name, address, city, state, zipcode):    try:        # your code as before        dom = json.loads(r.text)        return {k: dom['Records'][0][k] for k in fields}    # modify below: good practice to specify exactly which error(s) to catch    except:        return {}然后扩展您的字典系列:dcts = df.apply(lambda row: getData(key, row['Full Name'], row['Address'], row['City'],                                    row['State'], row['Zipcode']), axis=1)df = df.join(pd.DataFrame(dcts.tolist()))根据@spaniard 的评论,如果你想要所有可用的字段,你可以简单地使用:return json.loads(r.text)['Records'][0]
随时随地看视频慕课网APP

相关分类

Python
我要回答