我有一个使用numpy数组(MnthIdx,Val1,Val2,Val3)创建的数据框:
io.on('connection', socket =>{})
我是否有可能只用一步完成上述3个步骤。
答案 0 :(得分:1)
您可以将pivot_table
与3列用作参数values
。 Aggfunc=[np.mean]
可以省略,因为这是默认的聚合函数。最后,如果需要输出numpy array
,请使用values
:
print (pd.pivot_table(dfout3, index=['Idx'], values=['Col1', 'Col2', 'Col3']))
样品:
import pandas as pd
import numpy as np
MnthIdx = [1,2,2,3,3]
Val1 = [2,5,2,3,4]
Val2 = [6,1,5,3,5]
Val3 = [3,9,5,7,8]
dfout3 = pd.DataFrame({'Idx': MnthIdx,
'Col1': Val1,
'Col2': Val2,
'Col3': Val3})
MeanTable1 = pd.pivot_table(dfout3, index=['Idx'], values=['Col1'], aggfunc=[np.mean])
MeanVal1 = np.asarray(MeanTable1['mean'])
MeanTable2 = pd.pivot_table(dfout3, index=['Idx'], values=['Col2'], aggfunc=[np.mean])
MeanVal2 = np.asarray(MeanTable2['mean'])
MeanTable3 = pd.pivot_table(dfout3, index=['Idx'], values=['Col3'], aggfunc=[np.mean])
MeanVal3 = np.asarray(MeanTable3['mean'])
print (MeanTable1)
mean
Col1
Idx
1 2.0
2 3.5
3 3.5
print (MeanTable2)
mean
Col2
Idx
1 6
2 3
3 4
print (MeanTable3)
mean
Col3
Idx
1 3.0
2 7.0
3 7.5
print (pd.pivot_table(dfout3, index=['Idx'], values=['Col1', 'Col2', 'Col3']))
Col1 Col2 Col3
Idx
1 2.0 6.0 3.0
2 3.5 3.0 7.0
3 3.5 4.0 7.5
print (pd.pivot_table(dfout3, index=['Idx'], values=['Col1', 'Col2', 'Col3']).values)
[[ 2. 6. 3. ]
[ 3.5 3. 7. ]
[ 3.5 4. 7.5]]
答案 1 :(得分:1)
关闭jezael回答:
df = pd.pivot_table(dfout3, index=['Idx'], values=['Col1', 'Col2', 'Col3'])
means = [ np.asarray(df[x]) for x in list(df)]
'MeanTable1','MeanTable2','MeanTable3' = means
或
(MeanTable1,MeanTable2,MeanTable3) = [ np.asarray(df[x]) for x in list(df)]
这将为您提供数组方式。