如何将.fits文件中的操作数据转换为DataFram

2024-04-29 15:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含一些数据的.fits文件,从中我进行了一些操作,并希望将新数据(而不是整个.fits文件)存储为pd.数据帧. 数据来自一个名为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:list index must be integers or slices,not str”错误消息。你知道吗


Tags: 文件数据lambdafielddataframedatabetapd
1条回答
网友
1楼 · 发布于 2024-04-29 15:43:16

你得到这个是因为像sortedpab['ID']这样的访问。根据docsorted返回一个排序的列表。列表不接受字符串作为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)

相关问题 更多 >