如何将操纵数据从.fits文件转换为pandas DataFrame

问题描述 投票:1回答:1

我有一个包含一些数据的.fits文件,从中进行了一些操作,并希望将新数据(而不是整个.fits文件)存储为pd.DataFrame。数据来自名为pabdatazcut.fits的文件。

#Sorted by descending Paschen Beta flux
sortedpab = sorted(pabdatazcut[1].data , key = lambda data: data['PAB_FLUX'] , reverse = True )

unsorteddf = pd.DataFrame(pabdatazcut[1].data)

sortedpabdf = pd.DataFrame({'FIELD' : sortedpab['FIELD'],
                        'ID' :  sortedpab['ID'],
                        'Z_50' : sortedpab['Z_50'],
                        'Z_ERR' : ((sortedpab['Z_84'] - sortedpab['Z_50']) + (sortedpab['Z_50'] - sortedpab['Z_16'])) / (2 * sortedpab['Z_50']),
                        '$\lambda Pa\beta$' : 12820 * (1 + sortedpab['Z_50']),
                        '$Pa\beta$ FLUX' : sortedpab['PAB_FLUX'],
                        '$Pa\beta$ FLUX ERR' : sortedpab['PAB_FLUX_ERR']})

'' ''

当我尝试运行此错误消息时,我收到了'TypeError:列表索引必须是整数或切片,而不是str'错误消息。

python pandas astropy fits
1个回答
0
投票

您会因为sortedpab['ID']之类的访问而获得此密码。根据文档,sorted返回一个排序列表。列表不接受字符串作为id来访问元素。只能通过整数位置或切片访问它们。这就是错误要告诉您的内容。

不幸的是,由于我没有您的数据,所以我无法在计算机上对此进行测试,但是我想,您真正想要做的是这样的:

data_dict= dict()
for obj in sortedpab:
    for key in ['FIELD', 'ID', 'Z_50', 'Z_50', 'Z_ERR', 'Z_84', 'PAB_FLUX', 'PAB_FLUX_ERR']:
        data_dict.setdefault(key, list()).append(obj[key])

sortedpabdf = pd.DataFrame(data_dict)
# maybe you don't even need to create the data_dict but
# can pass the sortedpad directly to your data frame
# have you tried that already?
#
# then I would calculate the columns which are not just copied
# in the dataframe directly, as this is more convenient
# like this:
sortedpabdf['Z_ERR']= ((sortedpabdf['Z_84'] - sortedpabdf['Z_50']) + (sortedpabdf['Z_50'] - sortedpabdf['Z_16'])) / (2 * sortedpabdf['Z_50'])
sortedpabdf['$\lambda Pa\beta$']= 12820 * (1 + sortedpabdf['Z_50']),

sortedpabdf.rename({
        'PAB_FLUX': '$Pa\beta$ FLUX', 
        'PAB_FLUX_ERR': '$Pa\beta$ FLUX ERR'
    }, axis='columns', inplace=True)

cols_to_delete= [col for col in sortedpabdf.columns if col not in ['FIELD', 'ID', 'Z_50', 'Z_ERR', '$\lambda Pa\beta$', '$Pa\beta$ FLUX','$Pa\beta$ FLUX ERR'])
sortedpabdf.drop(cols_to_delete, axis='columns', inplace=True)
© www.soinside.com 2019 - 2024. All rights reserved.