Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 应用函数导致列表索引超出范围_Python_Json_Pandas_Apply - Fatal编程技术网

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

Python 应用函数导致列表索引超出范围,python,json,pandas,apply,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.loa

我试图修改整列的值,但列表超出范围的问题一直存在。这是我的全部代码:

# 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
理想情况下,我想从以下位置更改
位置
列:

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
注意,这假设该条目至少包含一个元素,则第一个元素是字典。代码的问题是您试图访问空数组的第一个(索引0)元素

编辑

要根据您的评论删除[{}],请执行以下操作:

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

显示数据\u norm.head()以获得更好的帮助。然而,听起来data_norm index不是整数,或者在数据中没有0least@Boud刚刚更新了原始帖子如何删除每个值周围的
[{}]
?例如,我想删除
[{}]
以仅获取
华盛顿州西雅图
data_norm.locations = data_norm.locations.apply(lambda x:
                                                x[0].get('name', '') 
                                                if len(x) > 0 else ''
                                                )