【发布时间】:2015-10-30 06:56:13
【问题描述】:
在我开始解释之前,这是我的一些数据示例:
PP04-O3N2SNpos log(O/H) + 12 positive error! negative error! nuclear metallicity NED calculated virgo infall distance in Kpc
9.04 0.24 -0.09 - -
8.76 0.17 -0.02 - 4.61
8.92 0.04 -0.04 9.03 2.97297
9.22 0.04 -0.04 - 8.24493
8.78 0.44 -0.24 9.23 10.25775
8.96 0.07 -0.2 9.05 7.2698
8.78 0.03 -0.03 8.48 2.02958
所以 PP04 是 NED 计算距离中心的金属丰度,而核金属丰度是中心的金属丰度。我试图找出是否存在某种方程式,如果我知道核金属丰度和与中心的距离,我就可以计算出 PP04。它看起来像这样:
'PP04' - 'nuclear metallicity' = distance * gradient
渐变是我要找的。p>
为此,我编写了一个代码来拟合所有数据,因此核金属丰度为零,然后我可以求解梯度并绘制数据图表,但我的代码存在一些问题。
import matplotlib.pyplot as plt
import pandas as pd
from pandas import *
from matplotlib import *
import traceback
import numpy as np
#import data into a pandas dataframe called df
df = pd.DataFrame.from_csv('Combined data.csv')
df = df.dropna()
#drop the nulls
print df
y = df['PP04-O3N2SNpos log(O/H)+12'] - df['nuclear metallicity']
yerr = np.array([(df['negative error!'],df['positive error!'])]).T
x = df['NED calculated virgo infall distance in Kpc']
intercept, gradient = np.polyfit(x,y,1)
print(intercept,gradient)
#to make a graph using the data
plt.errorbar(x,y,yerr,fmt = 'r-')
plt.xlabel('Distance from center in kpc')
plt.ylabel('PP04-O3N2SNpos log(O/H)+12')
plt.title('Central metallicity vs SN metallicity')
plt.show()
另一个错误我得到了这个
TypeError: cannot concatenate 'str' and 'float' objects
我对 python 很陌生,所以我确信我的代码还有其他问题,如果您也能提供帮助,我们将不胜感激。我不确定我绘制数据的方式是否正确,但我无法检查其他错误。
编辑: 我使用下面的帮助来更改我的代码,所以现在它正在使用
pd.read_csv('Combined data.csv').dtypes
pd.read_csv('Combined data.csv',na_values = '-').dtypes
df = pd.read_csv('Combined data.csv',na_values = '-')
但现在我得到了错误
TypeError: unsupported operand type(s) for -: 'float' and 'str'
这是回溯。
【问题讨论】:
-
1) 显然,当您获得上面显示的回溯时,
KeyError没有发生,因此这意味着您已经解决了导致它的原因。也许将它从问题中删除是有意义的。 2) 错误似乎表明您的x数组包含字符串而不是浮点数。检查最后一列的类型并在必要时进行转换。 -
我的猜测是,代表缺失值的连字符可能会阻止
pandas将列转换为浮点数。尝试使用read_csv的na_values参数。 -
回溯中没有发生 KeyError 的原因是因为我删除了说 df['nuclear metality'] 的部分,以查看其他 df 是否也出现错误,但后来我得到了上面的错误。所以我仍然有 KeyError 但我想我应该更清楚。感谢您的帮助,我会尝试您的建议。
-
在任何情况下,最好每个问题询问一个编程问题。您可以尝试打印
df.columns以查看列名中是否有空格或类似的内容。 -
感谢您的建议。我使用您在下面建议的内容将连字符作为 NaN 替代品,但我仍然收到一个我认为相关的错误。我在上面编辑了答案以反映我的更改。
标签: python pandas matplotlib typeerror