如何对整个Pandas MultiIndex进行字符串操作?

How to perform string operation on an entire Pandas MultiIndex?

我有一个带有两级列索引的 pandas 数据框。它是从电子表格中读取的,作者在电子表格中使用了大量空格来完成诸如对齐之类的事情(例如,一列称为 'Tank #')。

我已经能够单独删除关卡上的空白...

level0 = raw.columns.levels[0].str.replace('\s', '', regex=True)
level1 = raw.columns.levels[1].str.replace('\s', '', regex=True)
raw.columns.set_levels([level0, level1], inplace=True)

...但我很好奇是否有一种方法可以做到这一点而不必一次更改每个级别。

我试过了raw.columns.set_levels(raw.columns.str.replace('\s', '', regex=True) 但得到了 AttributeError: Can only use .str accessor with Index, not MultiIndex.

这是数据的一个小样本子集——我对 SO table 格式的最佳尝试 :D,然后是一张图片,其中我用黄色突出显示了收到的索引。

Run Info Run Info Run Data Run Data
run # Tank # Step A conc. %
ph
0 6931 5 5.29 33.14
1 6932 1 5.28 33.13
2 6933 2 5.32 33.40
3 6934 3 5.19 32.98

感谢您的任何见解!

编辑:添加 to_dict()

df.to_dict()
Out[5]: 
{'Unnamed: 0': {0: nan, 1: 0.0, 2: 1.0, 3: 2.0, 4: 3.0, 5: 4.0},
 'Run Info': {0: 'run #',
  1: '6931',
  2: '6932',
  3: '6933',
  4: '6934',
  5: '6935'},
 'Run Info.1': {0: 'Tank                             #',
  1: '5',
  2: '1',
  3: '2',
  4: '3',
  5: '4'},
 'Run Data': {0: 'Step A\npH',
  1: '5.29',
  2: '5.28',
  3: '5.32',
  4: '5.19',
  5: '5.28'},
 'Run Data.1': {0: 'concentration',
  1: '33.14',
  2: '33.13',
  3: '33.4',
  4: '32.98',
  5: '32.7'}}

怎么样rename:

import re

df.rename(columns=lambda x: re.sub('\s+', ' ', x.strip() ),inplace=True)

如果您不想保留任何空格,可以将 ' ' 替换为 ''