Python 将4列合并为两列

Python 将4列合并为两列,python,pandas,Python,Pandas,我有一个重复4列的数据框,我想将其合并为2列 Product ID Year_X Month_X Year_Y Month_Y 1 2020 1 2014 11 1 2019 2 2018 10 2 2022 5 2010 8 2

我有一个重复4列的数据框,我想将其合并为2列

Product ID     Year_X     Month_X     Year_Y    Month_Y
    1            2020         1        2014       11
    1            2019         2        2018       10
    2            2022         5        2010       8
    2            2021         1        2019       9
   
输出应如下所示:

Product ID     Year     Month
    1          2014      11
    1          2018      10
    1          2019      2
    1          2020      1
    2          2010      8
    2          2019      9
    2          2021      1
    2          2022      5

谢谢

首先通过
重置索引
创建唯一索引,然后您可以使用
从宽到长

print (pd.wide_to_long(df.reset_index(), stubnames=["Year", "Month"], 
                       i="index", j="Key", sep="_", suffix="\w*")
         .reset_index(drop=True))

   Product ID  Year  Month
0           1  2020      1
1           1  2019      2
2           2  2022      5
3           2  2021      1
4           1  2014     11
5           1  2018     10
6           2  2010      8
7           2  2019      9

首先通过
reset\u index
创建唯一索引,然后可以使用
wide\u to\u long

print (pd.wide_to_long(df.reset_index(), stubnames=["Year", "Month"], 
                       i="index", j="Key", sep="_", suffix="\w*")
         .reset_index(drop=True))

   Product ID  Year  Month
0           1  2020      1
1           1  2019      2
2           2  2022      5
3           2  2021      1
4           1  2014     11
5           1  2018     10
6           2  2010      8
7           2  2019      9

您可以通过将已有的数据帧分离到所需的列中并删除后缀来创建两个新的数据帧。然后用熊猫壳把它们放在一起。sort_值按您想要的顺序排列

df1 = df[['Product ID', 'Year_X', 'Month_X']].rename(columns={"Year_X": "Year", "Month_X": "Month"})
df2 = df[['Product ID', 'Year_Y', 'Month_Y']].rename(columns={"Year_Y": "Year", "Month_Y": "Month"})
pd.concat([df1, df2]).sort_values(by=['Product ID', 'Year']).reset_index(drop=True)
输出为

   Product ID  Year  Month
0           1  2014     11
1           1  2018     10
2           1  2019      2
3           1  2020      1
4           2  2010      8
5           2  2019      9
6           2  2021      1
7           2  2022      5

您可以通过将已有的数据帧分离到所需的列中并删除后缀来创建两个新的数据帧。然后用熊猫壳把它们放在一起。sort_值按您想要的顺序排列

df1 = df[['Product ID', 'Year_X', 'Month_X']].rename(columns={"Year_X": "Year", "Month_X": "Month"})
df2 = df[['Product ID', 'Year_Y', 'Month_Y']].rename(columns={"Year_Y": "Year", "Month_Y": "Month"})
pd.concat([df1, df2]).sort_values(by=['Product ID', 'Year']).reset_index(drop=True)
输出为

   Product ID  Year  Month
0           1  2014     11
1           1  2018     10
2           1  2019      2
3           1  2020      1
4           2  2010      8
5           2  2019      9
6           2  2021      1
7           2  2022      5
此函数可能有帮助此函数可能有帮助