我有一个 Python 列表 Tmp,如下所示:
A1 A2 B1 B2 C1 C2
0 17.387 17.470 19.93 13.29 19.93 19.93
1 17.680 17.896 21.85 14.57 21.86 21.86
2 17.787 17.228 24.46 16.30 24.45 24.45
我使用这段代码来选择不同的列:
cols1 = [col for col in cols if '1' in col]
combined1 = combined[cols1]
cols2 = [col for col in cols if '2' in col]
combined21 = combined[cols2]
我想让一个列表看起来像:
A1 A2
0 17.387 17.470
1 17.680 17.896
2 17.787 17.228
3 B1 B2 #I also want to delet the titles in between
4 19.93 13.29
5 21.85 14.57
6 24.46 16.30
7 C1 C2
8 19.93 19.93
9 21.86 21.86
10 24.45 24.45
我尝试了pd.concat、append,它们似乎都不起作用。 你有什么解决办法? 提前致谢!
请您参考如下方法:
您可以使用 boolean mask 获取两个子数据帧(用于 1 索引和 2 索引) . Unstacking将把每一个变成一个系列。然后你可以concat这些系列以获得您的结果。
m1 = df.columns.str.endswith('1')
df1 = df.loc[:, m1].unstack().reset_index(drop=True)
df2 = df.loc[:, ~m1].unstack().reset_index(drop=True)
pd.concat((df1, df2), axis=1, ignore_index=True)
返回
0 1
0 17.387 17.470
1 17.680 17.896
2 17.787 17.228
3 19.930 13.290
4 21.850 14.570
5 24.460 16.300
6 19.930 19.930
7 21.860 21.860
8 24.450 24.450
