gpt4 book ai didi

python - Pandas 表示跨多个列

转载 作者:行者123 更新时间:2023-11-30 22:53:58 25 4
gpt4 key购买 nike

我有一个使用 numpy 数组(MnthIdx、Val1、Val2、Val3)创建的数据框:

import pandas as pd
import numpy as np

dfout3 = pd.DataFrame({'Idx': MnthIdx,
'Col1': Val1,
'Col2': Val2,
'Col3': Val3)})

MeanTable1 = pd.pivot_table(dfout3, index=['Idx'], values=['Val1'], aggfunc=[np.mean])
MeanVal1 = np.asarray(MeanTable1['mean'])
MeanTable2 = pd.pivot_table(dfout3, index=['Idx'], values=['Val2'], aggfunc=[np.mean])
MeanVal2 = np.asarray(MeanTable2['mean'])
MeanTable2 = pd.pivot_table(dfout3, index=['Idx'], values=['Val3'], aggfunc=[np.mean])
MeanVal3 = np.asarray(MeanTable3['mean'])

是否有可能我只需 1 步即可完成上述 3 步。

最佳答案

您可以使用pivot_table有 3 列作为参数Aggfunc=[np.mean] 可以省略,因为这是默认聚合函数。最后,如果需要输出为 numpy 数组,请使用 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]]

关于python - Pandas 表示跨多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37974475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com