我正在尝试修改整个值列,但是列表不断超出范围,我一直遇到问题。这是我的整个代码:
# 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
最佳答案
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 ''
)
关于python - 应用功能导致列表索引超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41946703/