Tim*_*art 10 python regression numpy matplotlib pandas
我在pandas中有一个数据帧,用于生成散点图,并希望为绘图包含回归线.现在我正试着用polyfit做这件事.
这是我的代码:
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from numpy import *
table1 = pd.DataFrame.from_csv('upregulated_genes.txt', sep='\t', header=0, index_col=0)
table2 = pd.DataFrame.from_csv('misson_genes.txt', sep='\t', header=0, index_col=0)
table1 = table1.join(table2, how='outer')
table1 = table1.dropna(how='any')
table1 = table1.replace('#DIV/0!', 0)
# scatterplot
plt.scatter(table1['log2 fold change misson'], table1['log2 fold change'])
plt.ylabel('log2 expression fold change')
plt.xlabel('log2 expression fold change Misson et al. 2005')
plt.title('Root Early Upregulated Genes')
plt.axis([0,12,-5,12])
# this is the part I'm unsure about
regres = polyfit(table1['log2 fold change misson'], table1['log2 fold change'], 1)
plt.show()
但是我收到以下错误:
TypeError: cannot concatenate 'str' and 'float' objects
有谁知道我在哪里出错?我也不确定如何将回归线添加到我的情节中.关于我的代码的任何其他一般性评论也将非常感激,我仍然是初学者.
Dan*_*lan 23
而不是取代'#DIV/0!' 手动,强制数据为数字.这会同时执行两项操作:它确保结果是数字类型(不是str),并且它可以替换NaN任何无法解析为数字的条目.例:
In [5]: Series([1, 2, 'blah', '#DIV/0!']).convert_objects(convert_numeric=True)
Out[5]: 
0     1
1     2
2   NaN
3   NaN
dtype: float64
这应该可以解决您的错误.但是,在对数据进行拟合的一般主题上,我方便地使用两种方式来做到这一点,我比polyfit更喜欢.两者中的第二个更强大(并且可能返回有关统计信息的更详细信息),但它需要statsmodel.
from scipy.stats import linregress
def fit_line1(x, y):
    """Return slope, intercept of best fit line."""
    # Remove entries where either x or y is NaN.
    clean_data = pd.concat([x, y], 1).dropna(0) # row-wise
    (_, x), (_, y) = clean_data.iteritems()
    slope, intercept, r, p, stderr = linregress(x, y)
    return slope, intercept # could also return stderr
import statsmodels.api as sm
def fit_line2(x, y):
    """Return slope, intercept of best fit line."""
    X = sm.add_constant(x)
    model = sm.OLS(y, X, missing='drop') # ignores entires where x or y is NaN
    fit = model.fit()
    return fit.params[1], fit.params[0] # could also return stderr in each via fit.bse
要绘制它,做一些类似的事情
m, b = fit_line2(x, y)
N = 100 # could be just 2 if you are only drawing a straight line...
points = np.linspace(x.min(), x.max(), N)
plt.plot(points, m*points + b)