如何使用 python 在多索引数据框中将时间戳列名称重命名为 string/object

How to rename timestamp column names to string/object in multiindex dataframe using python

数据框:df

None  | A  B   volumeshare    volumeshare
X     |         2020-10-1      2020-11-1
---------------------------------------
0     | e1 f1      12            65    
1     | e1 f2      23            20     
2     | e1 f3      0             91    
3     | e2 f1      76            3     
4     | e2 f2      89            33    

我希望实现以下目标 -

  1. 只有顶行以 X、A、B、2020-10-1、2020-11-1 作为列名称的顺序。
  2. 第 3 列和第 4 列有时间戳名称(2020-10-1 和 2020-11-1),需要将其替换为字符串,分别为 Oct-20 和 Nov-20。

预期输出

X     | A   B      Oct-20       Nov-20
---------------------------------------
0     | e1 f1      12            65    
1     | e1 f2      23            20     
2     | e1 f3      0             91    
3     | e2 f1      76            3     
4     | e2 f2      89            33    

在列表理解中使用自定义 lambda 函数:

def f(a, b):
    d = pd.to_datetime(b, errors='coerce')
    return d.strftime('%b-%y') if pd.notna(d) else a
   
df.columns = [f(a, b) for a, b in df.columns]
print (df)
    A   B  Oct-20  Nov-20
0  e1  f1      12      65
1  e1  f2      23      20
2  e1  f3       0      91
3  e2  f1      76       3
4  e2  f2      89      33