简体   繁体   English

如何将值添加到熊猫数据框中的空列?

[英]How to add values into empty column in pandas dataframe?

I'm trying to add values into a new pandas column sp['New Address'] by using a Google Maps API Key and a for-loop that uses the addresses in the column sp['ASL Address (PAPER)-REFERENCE'] as a string query. 我正在尝试通过使用Google Maps API密钥和一个使用sp['ASL Address (PAPER)-REFERENCE']列中地址的for循环将值添加到新的pandas列sp['New Address'] 。作为字符串查询。

I've tried to create an empty list ( addresses ) that appends the searched addresses when the for-loop is run, and then run another for-loop that is supposed to loop through each row in sp['New Address'] and paste the addresses searched in the original for-loop: 我尝试创建一个空列表( addresses ),在运行for循环时将其添加到搜索到的地址之后,然后运行另一个应循环通过sp['New Address']每一行并粘贴的for循环在原始for循环中搜索的地址:

for address in sp['ASL Address (PAPER)-REFERENCE']:
    api_key = "API Key"
    url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
    query = address
    r = requests.get(url + 'query=' + query + '&key=' + api_key)
    x = r.json()
    z = x['results']
    for i in range(len(z)):
        for row in sp['New Address']:
            addresses = []
            sp['New Address'] = addresses.append((z[i]['formatted_address']))

I expected the rows in sp['New Address'] to be filled with an address such as '21 Laurel Brook Rd, Middletown, CT 06457, USA'. 我希望sp['New Address']中的行会填充一个地址,例如“美国CT 06457 Middletown的21 Laurel Brook Rd”。 However whenever I run the code, sp['New Address'] is still empty. 但是,每当我运行代码时, sp['New Address']仍然为空。

Your bug is simply that .append() on a list always returns None , because it works in-place 您的错误很简单, 就是列表上的.append()始终返回None ,因为它可以就地工作

(But if you'd attempted to debug this with a few humble print statements in each loop, you would have found that by yourself) (但是,如果您尝试在每个循环中使用一些不起眼的打印语句来调试它,那么您将自己发现这一点)

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

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