要按照您的要求取消透视或堆叠熊猫数据帧,您可以使用pandas库中的pivot和unstack函数。
示例代码:
import pandas as pd
# 创建数据帧
df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'two', 'two', 'one', 'one'],
'C': ['x', 'y', 'x', 'y', 'x', 'y'],
'D': [1, 2, 3, 4, 5, 6]})
# 透视数据帧
pivot_df = df.pivot(index='A', columns='B', values='D')
print(pivot_df)
输出结果:
B one two
A
bar 5 4
foo 1 3
在上述示例中,我们通过指定index、columns和values参数,将原始数据帧透视为以'A'列为行索引,'B'列为列索引,'D'列为值的新数据帧。
示例代码:
import pandas as pd
# 创建堆叠数据帧
stacked_df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar'],
'B': ['one', 'one', 'two', 'two', 'three', 'three'],
'C': ['x', 'y', 'x', 'y', 'x', 'y'],
'D': [1, 2, 3, 4, 5, 6]}).set_index(['A', 'B'])
# 取消堆叠数据帧
unstacked_df = stacked_df.unstack()
print(unstacked_df)
输出结果:
C D
B one two one two
A
bar y x 2 4
foo x x 1 3
在上述示例中,我们通过调用unstack函数,将原始数据帧中的堆叠数据重新排列为透视形式。
以上是按照您的要求给出的取消透视或堆叠熊猫数据帧的方法。请注意,这只是一种通用的方法,具体的实现可能因数据结构和需求而有所不同。
领取专属 10元无门槛券
手把手带您无忧上云