简单解释python unstack()

2024-10-17 06:29:23 发布

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

我试图在重写python代码之前对其进行注释,以避免由于an error而取消unstack()。当我向自己解释unstack时,即使在阅读了文档并看到了输出之后,我也感到困惑。有人能解释它的作用而不使用“pivot a level”这样的短语吗?在

Definition来自文档:

Pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels. If the index is not a MultiIndex, the output will be a Series (the analogue of stack when the columns are not a MultiIndex). The level involved will automatically get sorted.

下面是我试图注释的代码:

import numpy as np
import pandas as pd
from numpy.core.defchararray import add

d = {'vote': [100, 50,1,23,55,67,89,44], 
     'vote2': [10, 2,18,26,77,99,9,40], 
     'ballot1': ['a','b','a','a','b','a','c','c'],
     'voteId':[1,2,3,4,5,'aaa',7,'NaN']}
df1=pd.DataFrame(d)
#######################################################################
print(df1)
#Set the DataFrame index (row labels) using columns voteId and ballot1
s=df1[:10].set_index(['voteId','ballot1'],verify_integrity=True)
print(s)
#unstack (default -1). ?????
# s=s.unstack()
# s.columns=s.columns.map('(ballot1={0[1]}){0[0]}'.format) 
# dflw=pd.DataFrame(s)
# print(df1)
# print(dflw)

Tags: columnsofthe代码importdataframeindexlabels
1条回答
网友
1楼 · 发布于 2024-10-17 06:29:23

DataFrame.unstack()只需移动(“透视”)多索引(层次索引)数据帧的某些级别,使其成为列标签而不是行标签。文档中有明确的例子。在

相关问题 更多 >