使用 Pandas 重新排列具有相同列标题的数据帧单元格



我有这个 df,我用 pandas.read_excel(( 从 excel 文件中读取它:

ID A B
C A B C A B C 10 A1 B1 C1 A4 B4 C4 A7 B7 C7 20 A2 B2 C2 A5 B5 C5 A8 B8 C8 30 A3 B3 C3 A6 B6 C6 A9 B9 C9 我

怎样才能把它改成这样的df_1:

ID A B C     10 A1 B1 C1    20 A2 B2 C2    30 A3 B3 C3    10 A4 B4 C4 20 A5 B5 C5 30 A6 B6 C6 10 A7 B7 C7 20 A8 B8 C8 30 A9 B9 C9

您可以在列中创建MultiIndex,以便按cumcount计算重复的列名,然后可以通过stack进行整形,最后通过reset_index进行一些数据清理:

df = df.set_index('ID')
s = df.columns.to_series()
df.columns = [df.columns, s.groupby(s).cumcount()]
df = df.stack().sort_index(level=1).reset_index(level=1, drop=True).reset_index()
print (df)
ID   A   B   C
0  10  a1  b1  c1
1  20  a2  b2  c2
2  30  a3  b3  c3
3  10  a4  b4  c4
4  20  a5  b5  c5
5  30  a6  b6  c6
6  10  a7  b7  c7
7  20  a8  b8  c8
8  30  a9  b9  c9

这是使用列表理解和pd.concat的另一种方法

df1 = df.set_index('ID')
n=3 #The number of times your column headers repeat
pd.concat([df1.iloc[:,i:i+n] for i in range(0,df1.shape[1],n)]).reset_index()

输出:

ID   A   B   C
0  10  a1  b1  c1
1  20  a2  b2  c2
2  30  a3  b3  c3
3  10  a4  b4  c4
4  20  a5  b5  c5
5  30  a6  b6  c6
6  10  a7  b7  c7
7  20  a8  b8  c8
8  30  a9  b9  c9

最新更新