stocks= ['Apple','Raytheon','Amazon']
df = pd.DataFrame(data=[[10,11,12,13,5,2],[5,6,7,7,7,1]],
columns=['2020-12-31','2019-12-31','2020-09-26','2019-09-28','2020-01-01','2019-01-01'], index=['cash','inventory'])我把这份股票和他们的资产负债表列在一张数据里。我想把前2列(2020-12-31,2019-12-31)归入苹果,后两列归雷神( Raytheon ),后两列归亚马逊。
如何在Python中实现这一点?
发布于 2021-06-16 11:52:56
尝试使用np.repeat扩展stocks列表,然后使用zip并使用MultiIndex.from_tuples
df.columns = pd.MultiIndex.from_tuples(zip(np.repeat(stocks, 2), df.columns))df
Apple Raytheon Amazon
2020-12-31 2019-12-31 2020-09-26 2019-09-28 2020-01-01 2019-01-01
cash 10 11 12 13 5 2
inventory 5 6 7 7 7 1https://stackoverflow.com/questions/68002025
复制相似问题