如何替换pandas多重索引中的字符串?

2024-06-12 11:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,有一个大的多重索引,来源于大量的csv文件。其中一些文件在不同的标签中有错误,例如“window”被拼错为“winZZw”,当我用df.xs('window', level='middle', axis=1)选择所有窗口时,就会出现问题。在

所以我需要一种简单地将winZZw替换为window。在

这是一个非常小的df示例:(假设数据和'roof', 'window'…字符串来自一些复杂的文本阅读器)

header = pd.MultiIndex.from_product(['roof', 'window', 'basement'], names = ['top', 'middle', 'bottom'])
dates = pd.date_range('01/01/2000','01/12/2010', freq='MS')
data = np.random.randn(len(dates))
df = pd.DataFrame(data, index=dates, columns=header)
header2 = pd.MultiIndex.from_product(['roof', 'winZZw', 'basement'], names = ['top', 'middle', 'bottom'])
data = 3*(np.random.randn(len(dates)))
df2 = pd.DataFrame(data, index=dates, columns=header2)
df = pd.concat([df, df2], axis=1)
header3 = pd.MultiIndex.from_product(['roof', 'door', 'basement'], names = ['top', 'middle', 'bottom'])
data = 2*(np.random.randn(len(dates)))
df3 = pd.DataFrame(data, index=dates, columns=header3)
df = pd.concat([df, df3], axis=1)

现在我想xs一个新的数据帧,它适用于所有在中间层有窗口的房屋:windf = df.xs('window', level='middle', axis=1)

但这显然漏掉了拼错的winZZw。在

那么,我如何将winZZw替换为window

我发现的唯一方法是使用set_levels,但如果我理解正确,我需要将它提供给整个级别,即

^{pr2}$

但这有两个问题:

  • 我需要将整个索引传递给它,这在这个示例中很容易,但是对于具有数百个标签的千列df来说,这是不可能/愚蠢的。在
  • 它似乎需要把列表倒过来(现在,我在df中的第一个条目的中间是门,而不是窗口)。这可能是可以修复的,但看起来很奇怪

我可以通过xs创建一个只有winZZws的新df,然后用set_levels(df.shape[1]*[u'window'], level='middle')设置级别,然后再次将其合并在一起,但是我想有一个更直接的类似于str.replace('winZZw', 'window')的方法,但是我不知道怎么做。在


Tags: 数据frommiddledfdataproductwindowlevel
1条回答
网友
1楼 · 发布于 2024-06-12 11:41:41

使用rename指定级别:

header = pd.MultiIndex.from_product([['roof'],[ 'window'], ['basement']], names = ['top', 'middle', 'bottom'])
dates = pd.date_range('01/01/2000','01/12/2010', freq='MS')
data = np.random.randn(len(dates))
df = pd.DataFrame(data, index=dates, columns=header)
header2 = pd.MultiIndex.from_product([['roof'], ['winZZw'], ['basement']], names = ['top', 'middle', 'bottom'])
data = 3*(np.random.randn(len(dates)))
df2 = pd.DataFrame(data, index=dates, columns=header2)
df = pd.concat([df, df2], axis=1)
header3 = pd.MultiIndex.from_product([['roof'], ['door'], ['basement']], names = ['top', 'middle', 'bottom'])
data = 2*(np.random.randn(len(dates)))
df3 = pd.DataFrame(data, index=dates, columns=header3)
df = pd.concat([df, df3], axis=1)

df = df.rename(columns={'winZZw':'window'}, level='middle')
print(df.head())

top             roof                    
middle        window                door
bottom      basement  basement  basement
2000-01-01 -0.131052 -1.189049  1.310137
2000-02-01 -0.200646  1.893930  2.124765
2000-03-01 -1.690123 -2.128965  1.639439
2000-04-01 -0.794418  0.605021 -2.810978
2000-05-01  1.528002 -0.286614  0.736445

相关问题 更多 >