如何将熊猫数据框的相邻列分为三组?

时间:2020-10-16 10:43:10

标签: python pandas dataframe group-by pandas-groupby

 1  2  3  4  5  6  7  8  9  10  

 q  w  e  r  t  y  u  i  o   v
 p  a  s  d  f  g  h  j  k  b

I would like to form three groups
Group 1 = columns 2,3,4
Group 2 = columns 5,6,7
Group 3 = columns 8,9,10

我如何使用pandas groupby做到这一点?实际的数据帧有大约200个这样的行,它们被命名为“ 2000-01,2000-02,2000-03,2000-04,2000-05 2000-06,2000-07 ... 2015-11,2015-12 ,2016-01,2016-02,2016-03,2016-04,2016-05,2016-06,2016-07,2016-08“,我想获取每个季度的平均值

1 个答案:

答案 0 :(得分:2)

我认为您不需要groupby

如果您不强调groupby,我相信您可以做类似的事情(df是您的dataframe变量):

group1 = df[["2","3","4"]]
group2 = df[["4","5","6"]]
group3 = df[["7","8","9"]]

更新

正如您提到的,此数据框的列数未知,因此我更喜欢更新代码:

#df is the dataframe variable
i = 1
columnsList = []
finalList   = []
for column in df.columns:
    
    if(i%3 ==0):
        columnsList.append(column)
        group         = df[columnsList]
        finalList.append(group)
        del columnsList[:]
    else:
        columnsList.append(column)
    i += 1

现在只需选择n = i+1的第n个元素(ifinalList是索引)作为您的第n个组并执行process.ta-da!