我需要使用最好的线来预测我的数据框中的值。我该怎么做?是否有一个函数,例如,我可以输入一年并获得预期寿命的预测值?
Year Life Expectancy
1930 59.7
1940 62.9
1950 70.2
1965 67.7
我将如何计算1948年的价值?
答案 0 :(得分:2)
我有一点时间,为了娱乐起见,使用了numpy.polyfit()
和.polyval()
的基于@ALollz注释的完整示例。
% matplotlib inline
import pandas as pd
import numpy as np
# Generate some test data with a trend.
data = pd.DataFrame(
{
'year': list(range(1900, 2000)),
'life_exp': np.linspace(50, 80, 100) * ((np.random.randn(100, ) * 0.1) + 1)
}
)
data[['life_exp']].plot()
给予:
# Fit coefficents.
coef = np.polyfit(data['year'], data['life_exp'], 1)
# Generate predictions for entire series.
data['predicted'] = pd.Series(np.polyval(coef, data['year']))
data[['life_exp', 'predicted']].plot()
这给了我们想要的结果:
我们可以预测单个年份:
# Passing in a single year.
x = 1981
print('Predicted life expectancy for {}: {:.2f} years'.format(x, np.polyval(coef, x)))
礼物:Predicted life expectancy for 1981: 72.40 years
希望这是正确的用法,我从中得到了一些答案:)
答案 1 :(得分:2)
您可以使用:
import seaborn as sns
sns.lmplot(data['Year'],data['Life Expectancy'],data)
根据线性回归,这将为您的给定数据拟合一条直线,还可以计算出其他任何值,例如1948年等。
有关文档,请参阅: https://seaborn.pydata.org/generated/seaborn.lmplot.html