应用函数导致列表索引超出范围

时间:2017-01-30 22:41:03

标签: python json pandas apply

我试图修改整列值,但我仍然遇到列表超出范围的问题。这是我的全部代码:

# Libraries
import json, requests
import pandas as pd
from pandas.io.json import json_normalize

# Set URL
url = 'https://api-v2.themuse.com/jobs'

# For loop to extract data
for i in range(100):
    data = json.loads(requests.get(
        url=url,
        params={'page': i}
    ).text)['results']

# JSON to PANDAS
data_norm = pd.read_json(json.dumps(data))

# Modify two columns' values
data_norm.locations = data_norm.locations.apply(lambda x: [{x[0]['name']}])
data_norm.publication_date = pd.to_datetime(data_norm.publication_date)

这里的问题是当我使用函数

data_norm.locations = data_norm.locations.apply(lambda x: [{x[0]['name']}]) 

我收到以下错误:

IndexError: list index out of range

理想情况下,我想从此更改location列:

0               [{'name': 'Seattle, WA'}]
1    [{'name': 'San Francisco Bay Area'}]
2             [{'name': 'Palo Alto, CA'}]
3                  [{'name': 'Reno, NV'}]
4                                      []
Name: locations, dtype: object

进入这个:

0                     Seattle, WA
1          San Francisco Bay Area
2                   Palo Alto, CA
3                        Reno, NV
4                                      
Name: locations, dtype: object

1 个答案:

答案 0 :(得分:2)

data_norm.locations = data_norm.locations.apply(lambda x:
                                                [{x[0].get('name', '')}] 
                                                if len(x) > 0 else []
                                                )

请注意,这假设如果该条目包含至少一个元素,则第一个元素是字典。您的代码的问题是您尝试访问数组为空的第一个(索引0)元素。

修改

根据您的评论删除[{}]:

data_norm.locations = data_norm.locations.apply(lambda x:
                                                x[0].get('name', '') 
                                                if len(x) > 0 else ''
                                                )