参考数据:
df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "times_A":[3, 23], "view_B":[1200, 300], "times_B":[5, 3]}) print(df.set_index("Code", inplace=True))
view_A times_A view_B times_B Code 1 3000 3 1200 5 2 2300 23 300 3
实现结果:
Code type view click 1 A 3000 3 2 A 2300 23 1 B 1200 5 2 B 300 3
1、使用stack()实现
相关文档:Python pandas.DataFrame.stack函数方法的使用
import pandas as pd df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "times_A":[3, 23], "view_B":[1200, 300], "times_B":[5, 3]}) df.columns = df.columns.str.split('_', expand=True) print(df.stack().rename_axis(['code', 'type']))
输出:
code type times view 1 A 3 3000 B 5 1200 2 A 23 2300 B 3 300
2、使用wide_to_long()实现
import pandas as pd df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "times_A":[3, 23], "view_B":[1200, 300], "times_B":[5, 3]}) print(pd.wide_to_long(df.reset_index(), ['view','times'], i='Code', j='type', sep='_', suffix='\\w+'))
输出:
Code type view times 1 A 3000 3 2 A 2300 23 1 B 1200 5 2 B 300 3
3、使用pivot_longer()实现
# pip install pyjanitor import pandas as pd import janitor df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "times_A":[3, 23], "view_B":[1200, 300], "times_B":[5, 3]}) print(df.pivot_longer(index='Code', names_to=('.value', 'type'), names_sep='_') .set_index(['Code', 'type']) )
输出:
Code type view times 1 A 3000 3 2 A 2300 23 1 B 1200 5 2 B 300 3