Python 中多索引 Pandas 数据帧的线性回归
Linear Regression on Multiindex Pandas Dataframe in Python
我正在尝试对随时间推移的年温度进行回归,并为每个经纬度坐标获得 slope/linear 趋势(回归生成的数字)(完整数据集有很多 lat/lon 地点)。我想用这个斜率值替换每个位置的年份和温度。我的最终目标是用 cartopy 映射这些趋势。
这是 pandas 多索引数据帧中的一些测试数据
tempanomaly
lat lon time_bnds
-89.0 -179.0 1957 0.606364
1958 0.495000
1959 0.134286
这是我的目标:
lat lon trend
-89.0 -179.0 -0.23604
这是我的回归函数
def regress(y):
#X is the year or index, y is the temperature
X=np.array(range(len(y))).reshape(len(y),1)
y = y.array
fit = np.polyfit(X, y, 1)
return (fit[0])
这是我尝试调用它的方式
reg = df.groupby(["lat", "lon"]).transform(regress)
我收到的错误是 TypeError: Transform function invalid for data types
。
在调试过程中,我发现每一行的回归是 运行(3 次,使用测试数据),而不是每个位置一次(测试数据中只有一个位置)。我相信问题出在我用来调用回归的方法上,但无法找出另一种方法来迭代并执行 lat/lon 对的回归——我感谢任何帮助!
我认为您的 regress
函数也有错误,因为在您的情况下 X
应该是一维向量。所以这里是固定的 regress
函数:
def regress(y):
#X is the year or index, y is the temperature
X = np.array(range(len(y)))
y = y.array
fit = np.polyfit(X, y, 1)
return (fit[0])
For pandas.DataFrame.transform
produced DataFrame will have same axis length as self. Pandas Documentation
因此 aggregate
是更适合您的情况。
reg = df.groupby(["lat", "lon"]).aggregate(trend=pd.NamedAgg('tempanomaly', regress)).reset_index()
产生:
lat lon trend
-89.0 -179.0 -0.236039
创建的示例数据如下:
lat_lon = [(-89.0, -179.0), (-89.0, -179.0), (-89.0, -179.0)]
index = pd.MultiIndex.from_tuples(lat_lon, names=["lat", "lon"])
df = pd.DataFrame({
'time_bnds':[1957,1958,1959],
'tempanomaly': [0.606364, 0.495000, 0.134286]
},index=index)
我正在尝试对随时间推移的年温度进行回归,并为每个经纬度坐标获得 slope/linear 趋势(回归生成的数字)(完整数据集有很多 lat/lon 地点)。我想用这个斜率值替换每个位置的年份和温度。我的最终目标是用 cartopy 映射这些趋势。
这是 pandas 多索引数据帧中的一些测试数据
tempanomaly
lat lon time_bnds
-89.0 -179.0 1957 0.606364
1958 0.495000
1959 0.134286
这是我的目标:
lat lon trend
-89.0 -179.0 -0.23604
这是我的回归函数
def regress(y):
#X is the year or index, y is the temperature
X=np.array(range(len(y))).reshape(len(y),1)
y = y.array
fit = np.polyfit(X, y, 1)
return (fit[0])
这是我尝试调用它的方式
reg = df.groupby(["lat", "lon"]).transform(regress)
我收到的错误是 TypeError: Transform function invalid for data types
。
在调试过程中,我发现每一行的回归是 运行(3 次,使用测试数据),而不是每个位置一次(测试数据中只有一个位置)。我相信问题出在我用来调用回归的方法上,但无法找出另一种方法来迭代并执行 lat/lon 对的回归——我感谢任何帮助!
我认为您的 regress
函数也有错误,因为在您的情况下 X
应该是一维向量。所以这里是固定的 regress
函数:
def regress(y):
#X is the year or index, y is the temperature
X = np.array(range(len(y)))
y = y.array
fit = np.polyfit(X, y, 1)
return (fit[0])
For
pandas.DataFrame.transform
produced DataFrame will have same axis length as self. Pandas Documentation
因此 aggregate
是更适合您的情况。
reg = df.groupby(["lat", "lon"]).aggregate(trend=pd.NamedAgg('tempanomaly', regress)).reset_index()
产生:
lat lon trend
-89.0 -179.0 -0.236039
创建的示例数据如下:
lat_lon = [(-89.0, -179.0), (-89.0, -179.0), (-89.0, -179.0)]
index = pd.MultiIndex.from_tuples(lat_lon, names=["lat", "lon"])
df = pd.DataFrame({
'time_bnds':[1957,1958,1959],
'tempanomaly': [0.606364, 0.495000, 0.134286]
},index=index)