python - 如何计算pandas中n行与groupby的相关性
问题描述
我在熊猫中有以下数据框
code tank var nozzle_1 nozzle_2 nozzle_3
123 1 23.34 12.23 54.56 12.22
123 1 22.32 11.32 7.89 3.45
123 1 21.22 19.93 5.54 5.66
123 1 21.34 12.23 54.56 22.22
123 1 32.32 13.32 4.89 32.45
123 1 32.22 29.93 23.54 23.66
123 2 23.34 12.23 54.56 12.22
123 2 22.32 11.32 7.89 3.45
123 2 21.22 19.93 5.54 5.66
123 2 21.34 12.23 54.56 22.22
123 2 32.32 13.32 4.89 32.45
123 2 32.22 29.93 23.54 23.66
我想找到喷嘴_1、喷嘴_2、喷嘴_3与var列按坦克分组的相关性,并为每3行获取相关性
我想要的数据框是
code tank nozzle_1 nozzle_2 nozzle_3
123 1 0.20 0.30 0.23
123 1 0.12 0.08 0.12
123 2 0.14 0.12 0.01
123 2 0.15 0.04 0.13
我正在关注熊猫
cols= df.columns[df.columns.str.contains(pat='nozzle_\d+$', regex=True)]
cols= np.array(cols)
def corrVar(df, cols):
for col in cols_to_scale:
for i in range(0, df.shape[0], 3):
df[col] = df.groupby('tank')[col, 'var'].corr()
return df
测试 = corrVar(df, cols)
但是,它并没有给我想要的结果。我们如何在熊猫中做到这一点?
解决方案
没有直接的解决方案,所以这是我的细分:
- 我们得到以开头的列的列索引
nozzle
- 我们得到列的列索引
var
GroupBy
打开code, tank
并计算每列数据帧前半部分的相关性nozzle
- 做同样的事情,但下半场
Concat
两半作为数据框相互final
重叠
cols_idx = [df.columns.get_loc(c) for c in df.filter(like='nozzle').columns]
var_idx = df.columns.get_loc('var')
df1 = pd.concat([
df.groupby(['code','tank']).apply(lambda x: x.iloc[:len(x)//2, var_idx].corr(x.iloc[:len(x)//2, idx])) for idx in cols_idx
], axis=1).reset_index()
df2 = pd.concat([
df.groupby(['code','tank']).apply(lambda x: x.iloc[len(x)//2:, var_idx].corr(x.iloc[len(x)//2:, idx])) for idx in cols_idx
], axis=1).reset_index()
df_final = pd.concat([df1,df2]).sort_values('tank').reset_index(drop=True)
输出
code tank 0 1 2
0 123 1 -0.826376 0.876202 0.703793
1 123 1 0.540176 -0.931286 0.614626
2 123 2 -0.826376 0.876202 0.703793
3 123 2 0.540176 -0.931286 0.614626
如果要正确重命名列
推荐阅读
- javascript - 仅当文本与 div 重叠时无法更改字体颜色
- python - 如何用NA所属行的平均值填充DataFrame中的NaN值,并返回新的dataframe
- ios - 从外部 url 打开使用 filemaker ios sdk (FIAS) 制作的应用程序显示错误弹出窗口
- webpack - Webpack 样式加载器与 mini-css-extract-plugin
- reactjs - Gatsby + ThemeProvider StyledComponents 的主题为空
- c# - 什么是“膨胀型”?
- oracle - Oracle:随机 ACL 错误
- ios - AudioKit:AKNodeRecorder 随机停止麦克风
- javascript - 如何使用 fofkJoin 获得多个结果然后使用结果?
- git - 在 Synology NAS 上启用 Gitlab LFS