矩阵乘法错误:无法将序列转换为<type'float'>

时间:2019-08-02 15:46:00

标签: python pandas matrix-multiplication

我正在尝试使用矩阵乘法将某些矩阵的ra和dec坐标转换为银河坐标,但出现错误。这里的代码:

    import pandas as pd
    import numpy as np
    from astropy.io import fits
    import astropy
    import matplotlib.pyplot as plt
    import math
    fits_filename="Gaia_DR2/gaiadr2_20pc.fits"
    df=pd.DataFrame()
    with fits.open(fits_filename) as data:
        df = pd.DataFrame(data[1].data)
    df.columns = [c.lower() for c in df.columns]
    print("Columns:")
    print(df.columns.values)
    print("\n\n")
    print("Number of stars: ")
    nstars=len(df)
    print(nstars)
    ra=df['ra']
    dec=df['dec']
    df["ra_radians"]=np.radians(df.ra)
    df["dec_radians"]=np.radians(df.dec)
    df["cosra"] = [np.math.cos(df['ra_radians'])]
    df["cosdec"] = [np.math.cos(df['dec_radians'])]
    df["sinra"] = [np.math.sin(df['ra_radians'])]
    df["sindec"] = [np.math.sin(df['dec_radians'])]
    df["xICRS"]=np.multiply[df['cosra'],df['cosdec']]
    df["yICRS"]=np.multiply[df['sinra'], df['sindec']]
    df["zICRS"] = df["sindec"]

错误:

 TypeError: cannot convert the series to <type 'float'>

我该如何解决?

1 个答案:

答案 0 :(得分:0)

我认为,这是因为np.math.cos之类的函数期望浮点数而不是序列数。它们不是“向量化的”。但不是这样做

df['cosra']= [np.math.cos(df['ra_radians'])]
df['xICRS']= np.multiply[df['cosra'],df['cosdec']]

你可以做

df['cosra']= df['ra_radians'].map(np.math.cos)
df['xICRS']= df['cosra'] * df['cosdec']

Map将函数(此处为np.math.cos)应用到系列的每个元素,并返回带有结果的系列。