我有一个字典列表(这是从数据库中获取一些数据的示例)。
并使用numpy.where子句,我希望将具有特定索引的所有项目放入另一个列表中
from astropy.coordinates import SkyCoord
from astropy import units as u
import numpy
from operator import itemgetter
from decimal import *
lightcurve_data = {}
lightcurve_data['stars'] = [{u'delta_j2000': Decimal('66.113525'), u'calibrated_error': 0.0442272797226906, u'id': 35549943L, u'filter': u'V', u'date': 2458008.64520255, u'calibrated_magnitude': Decimal('12.5425'), u'alpha_j2000': Decimal('325.777614')}, {u'delta_j2000': Decimal('66.113535'), u'calibrated_error': 0.0246241167187691, u'id': 38672301L, u'filter': u'R', u'date': 2458038.52371412, u'calibrated_magnitude': Decimal('11.8814'), u'alpha_j2000': Decimal('325.777077')}]
stars_for_filter = sorted(lightcurve_data['stars'], key=itemgetter('calibrated_magnitude'), reverse=True)
coord_list = SkyCoord(map(itemgetter('alpha_j2000'), stars_for_filter), map(itemgetter('delta_j2000'), stars_for_filter), frame='fk5', unit=u.degree)
index_array = [1., 1.]
median_ra = numpy.zeros(int(numpy.max(index_array)), dtype=float)
lightcurve_data['seperated'] = {}
for i in range(0, len(median_ra)):
check_in_index_array = numpy.where(index_array == i + 1)
key = 'some unique key'
# This bit works
median_ra[i] = numpy.median(coord_list[check_in_index_array[0]].ra.degree)
# The rest doesn't...
lightcurve_data['seperated'][key] = []
lightcurve_data['seperated'][key] = lightcurve_data['stars'][check_in_index_array[0]]
但是,运行此代码时,出现以下异常:
TypeError: only integer scalar arrays can be converted to a scalar index
有趣的是,check_in_index_array[0]
的相同用法可用于AstroPy SkyCoord的列表。
完整的回溯如下:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "[redacted]/views.py", line 1192, in lightcurve
lightcurve_data['seperated'][key] = lightcurve_data['stars'][check_in_index_array[0]]
TypeError: only integer scalar arrays can be converted to a scalar index
有什么办法可以解决此异常?还是以不同的方式来解决这个问题?
谢谢
会。
答案 0 :(得分:0)
基于@hpaulj's comment,我已经能够通过将lightcurve_data['stars']
从Python列表转换为NumPy数组来回答这个问题。
array_stars = numpy.asarray(lightcurve_data['stars'])
然后
lightcurve_data['seperated'][key] = array_stars[check_in_index_array[0]]
例外不再发生-一切正常。谢谢!