开发手册 欢迎您!
软件开发者资料库

Python pandas 将DataFrame两列合成一列的方法

本文主要介绍Python中,将DataFrame两列合成一列的方法,以及相关的示例代码。

参考数据:

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_BCode            1     3000        3          1200      52     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 pddf = 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  12002    A        23  2300     B         3   300

2、使用wide_to_long()实现

import pandas as pddf = 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  times1    A     3000      32    A     2300     231    B     1200      52    B      300      3

3、使用pivot_longer()实现

# pip install pyjanitorimport pandas as pdimport janitordf = 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  times1    A     3000      32    A     2300     231    B     1200      52    B      300      3