我有一个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]})
使用pivot_table()
和reset_index()
我可以将year的值移动到各个列中,但不能按其他列进行聚合
使用: pivotDF=pd.pivot\u表(df,索引=['state','county','columns='year') pivotDF=pivotDF.reset\u index()
让我靠近,但不是我需要的
我需要的是,另一个列标记count1和count2,在year列中有值。像这样的东西:
我知道一个DataFrame会把“state”和“county”的所有值都填好,这很好,但是我要把它输出到Excel,并且需要它看起来像这样,所以如果有办法使用这种格式,那将是一个额外的好处
非常感谢
你已经记下了大部分答案。只需添加一个带有
level=0
的堆栈,以在该级别而不是默认的年份级别上进行堆栈你在找
pivot
然后stack
相关问题 更多 >
编程相关推荐