3
我使用熊猫重塑一些字符串/数字值的响应,我遇到了一些有点不直观的行为。熊猫数据框堆叠与转轴
有人可以解释dataframes stacked
及以下pivoted
之间的区别,以及为什么pivoted2
提高了DataError
即使没有aggfunc
传递?
import pandas as pd
d = {'ID': pd.Series(['x']*3 + ['y']*3,index = range(6)),
'Count': pd.Series([1,2,1,1,1,1], index = range(6)),
'Value_type': pd.Series(['foo','foo','bar','foo','bar','baz'], index = range(6)),
'Value': pd.Series(range(1,7),index = range(6))}
df = pd.DataFrame(d)
d2 = {'ID': pd.Series(['x']*3 + ['y']*3,index = range(6)),
'Count': pd.Series([1,2,1,1,1,1], index = range(6)),
'Value_type': pd.Series(['foo','foo','bar','foo','bar','baz'], index = range(6)),
'Value': pd.Series(list('abcdef'),index = range(6))}
df2 = pd.DataFrame(d2)
restacked = df.set_index(['ID','Count','Value_type']).unstack()
print restacked
restacked2 = df2.set_index(['ID','Count','Value_type']).unstack()
print restacked2
pivoted = pd.pivot_table(df,rows = ['ID','Count'],cols = 'Value_type',values = 'Value')
print pivoted
## raises DataError('No numeric types to aggregate'),
## even though no aggregation function is passed.
pivoted2 = pd.pivot_table(df2,rows = ['ID','Count'],cols = 'Value_type',values = 'Value')
print pivoted2
谢谢,这工作完美。你能解释一下堆叠的数据框和旋转的数据框之间的区别吗? –
@MichaelK只是pivot_table不会标记(作为multiindex的第一行)您正在抓取的值,*除非*您传递了值列的列表。也就是说:restacked ['Value'] == pivoted。 –