【问题标题】:python replace string function throws asterix wildcard errorpython替换字符串函数抛出asterix通配符错误
【发布时间】:2015-12-14 12:27:03
【问题描述】:

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

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)


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

原文:

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')

我正在查看此链接:Changing columns names in Pandas with hierarchical columns

那位作者说它会在 0.15.0 变得更容易,所以我希望有更多最近更新的解决方案

【问题讨论】:

    标签: regex python-2.7 pandas wildcard


    【解决方案1】:

    您需要在末尾添加星号* 才能匹配字符串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: []
    

    【讨论】:

    • 感谢您的信息。所以现在我没有收到错误,但是(如上面的编辑中所述)通配符不能像我现在希望的那样工作
    • mm 感谢您的编辑。这很有意义,当我运行您的示例时,它可以工作。但是,当我使用我的数据框运行它并添加inplace=True 时,我得到了keyerror。但是,我认为这只是我的一部分。你会建议使用inplace=True,是吗?
    • 可能,但我没有你的真实数据和你的代码,但我认为上面应该可以正常工作
    • 啊,好吧,对不起,我最初没有更具体。我认为我遇到的问题是由于分层列。我会在上面更新..我应该早点指定这个。我不认为这会有所作为
    • 如果您有分层列,则无法重命名给定级别的单个值,您必须使用 setlevels 为该级别的所有列传递值列表
    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2016-10-08
    相关资源
    最近更新 更多