python 替换字符串函数抛出星号通配符错误

python replace string function throws asterix wildcard error

当我使用 * 时收到错误消息

raise error, v # invalid expression error: nothing to repeat

其他通配符,例如 ^ 可以正常工作。

代码行: df.columns = df.columns.str.replace('*agriculture', 'agri')

我正在使用 pandas 和 python

编辑: 当我尝试使用 / 转义时,通配符无法正常工作

In[44]df = pd.DataFrame(columns=['agriculture', 'dfad agriculture df'])

In[45]df
Out[45]: 
Empty DataFrame
Columns: [agriculture, dfad agriculture df]
Index: []

in[46]df.columns.str.replace('/*agriculture*','agri')
Out[46]: Index([u'agri', u'dfad agri df'], dtype='object')

我以为通配符应该输出Index([u'agri', u'agri'], dtype='object)


编辑: 我目前正在使用分层列,并且只想为该特定级别(级别 = 2)替换 agri

原文:

df.columns[0] = ('grand total', '2005', 'agriculture')
df.columns[1] = ('grand total', '2005', 'other')

期望:

df.columns[0] = ('grand total', '2005', 'agri')
df.columns[1] = ('grand total', '2005', 'other')

我现在正在看这个 link:Changing columns names in Pandas with hierarchical columns

作者说 0.15.0 会变得更容易所以我希望有更新的解决方案

您需要在末尾加上星号 * 才能匹配字符串 0 次或更多次,请参阅 docs:

In [287]:
df = pd.DataFrame(columns=['agriculture'])
df

Out[287]:
Empty DataFrame
Columns: [agriculture]
Index: []

In [289]:
df.columns.str.replace('agriculture*', 'agri')

Out[289]:
Index(['agri'], dtype='object')

编辑

根据您的新需求和实际需求,您可以使用 str.contains 查找匹配项,然后使用它构建字典以将旧名称映射到新名称,然后调用 rename:

In [307]:
matching_cols = df.columns[df.columns.str.contains('agriculture')]
df.rename(columns = dict(zip(matching_cols, ['agri'] * len(matching_cols))))

Out[307]:
Empty DataFrame
Columns: [agri, agri]
Index: []