将DataFrame列重塑为多列,将其他列重塑为行

2024-09-29 19:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个DataFrame,我需要将一列转换为多列,然后创建另一列来索引/标记新/多列的值

import pandas as pd

df = pd.DataFrame({'state':['AK','AK','AK','AK','AL','AL','AL','AL'], 'county':['Cnty1','Cnty1','Cnty2','Cnty2','Cnty3','Cnty3','Cnty4','Cnty4'], 
        'year':['2000','2001','2000','2001','2000','2001','2000','2001'], 'count1':[5,7,4,8,9,1,0,1], 'count2':[8,1,4,6,7,3,8,5]})

enter image description here

使用pivot_table()reset_index()我可以将year的值移动到各个列中,但不能按其他列进行聚合

使用: pivotDF=pd.pivot\u表(df,索引=['state','county','columns='year') pivotDF=pivotDF.reset\u index()

让我靠近,但不是我需要的

我需要的是,另一个列标记count1和count2,在year列中有值。像这样的东西:

enter image description here

我知道一个DataFrame会把“state”和“county”的所有值都填好,这很好,但是我要把它输出到Excel,并且需要它看起来像这样,所以如果有办法使用这种格式,那将是一个额外的好处

非常感谢


Tags: 标记dataframedfyearpdakstateal
2条回答

你已经记下了大部分答案。只需添加一个带有level=0的堆栈,以在该级别而不是默认的年份级别上进行堆栈

pd.pivot_table(df, index=['state', 'county'], columns='year', values=['count1', 'count2']) \
    .stack(level=0)

你在找pivot然后stack

s=df.pivot_table(index=['state','county'],columns='year',values=['count1','count2'],aggfunc='mean').stack(level=0)
s
Out[142]: 
year                 2000  2001
state county                   
AK    Cnty1  count1     5     7
             count2     8     1
      Cnty2  count1     4     8
             count2     4     6
AL    Cnty3  count1     9     1
             count2     7     3
      Cnty4  count1     0     1
             count2     8     5

相关问题 更多 >

    热门问题