[英]Pandas: Pivot a typed dataset
Suppose I have data in the following format:假设我有以下格式的数据:
Time, Type, Subtype, Value
0,A,Ab,1
0,A,Ac,2
0,B,Ba,1
And I need:我需要:
Time, Type-A-Ab-Value, Type-A-Ac-Value, Type-B-Ba-Value
0, 1, 2, 1
Is there a pandas primitive that will solve this problem in one stroke?是否有一个 pandas 原语可以一次性解决这个问题?
Use DataFrame.set_index
to set the multilevel index then use DataFrame.unstack
on the levels 1, 2
to reshape the dataframe, then use .map
to flatten the MultiIndex
columns: Use
DataFrame.set_index
to set the multilevel index then use DataFrame.unstack
on the levels 1, 2
to reshape the dataframe, then use .map
to flatten the MultiIndex
columns:
df1 = df.set_index(['Time', 'Type', 'Subtype']).unstack(level=[1, 2])
df1.columns = df1.columns.map(lambda s: 'Type-' + '-'.join(s[1:]) + '-Value')
OR, it is also possible to use DataFrame.pivot
:或者,也可以使用
DataFrame.pivot
:
df['pvt'] = 'Type-' + df['Type'] + '-' + df['Subtype'] + '-Value'
df1 = df.pivot('Time', 'pvt', 'Value').rename_axis(columns=None)
Result:结果:
print(df1)
Type-A-Ab-Value Type-A-Ac-Value Type-B-Ba-Value
Time
0 1 2 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.