【问题标题】:Replacing Index values using regex matching使用正则表达式匹配替换索引值
【发布时间】:2016-05-23 18:36:10
【问题描述】:

我正在尝试在 Pandas 系列中的索引中进行字符串替换。但是,目前它没有匹配或找到子字符串并将其替换为给定值。

我目前的系列:

index @12456 string_1 @54324 string_2 @34566 string_3 @57453 string_4 @67645 string_5 Name: value, dtype: object

为此,我试图从索引值中删除“@”符号。

我正在使用:

series.replace(to_replace={'index': {'@': ''}})

但是,它似乎与子字符串不匹配并返回初始系列。我缺少什么以及如何实现我的预期结果?

我的 pandas 版本目前是 0.15。

附:我也试过:

series.replace(to_replace={'index': {r'@': ''}})
series.replace(to_replace={'index': {r'\@': ''}})

更新

一些答案​​正在解决特定问题,但我需要一个更一般的案例。所以,如果系列是:

index other_index @12456 1 string_1 @54324 2 string_2 @34566 3 string_3 @57453 4 string_4 @67645 5 string_5 Name: value, dtype: object

如何在此处对索引应用相同的操作?哪一个对第一个措施和其他措施都有效?

【问题讨论】:

    标签: python regex python-2.7 pandas


    【解决方案1】:

    你可以这样做:

    series.index = series.index.map(lambda v: v.replace('@', ''))
    

    series.index = series.index.str.replace('@', '')
    

    对于多索引,这是一个可能的解决方案(虽然不是那么漂亮):

    # setting up the indices and the series
    arrays = [['@str1', '@str2'], [1, 2]]
    ind = pd.MultiIndex.from_arrays(arrays, names=['index', 'other_index'])
    series = pd.Series(['s1', 's2'], index=ind)
    
    # index  other_index
    # @str1  1              s1
    # @str2  2              s2
    # dtype: object
    
    vals = zip(*series.index.get_values()) ## values of indices reshaped into a list of tuples
    # [('@str1', '@str2'), (1L, 2L)]
    
    # find out where is the index that we want to change
    pos = series.index.names.index('index')
    # now we can modify the tuple by replacing the strings we do not want
    vals[pos] = tuple([x.replace('@', '') for x in vals[pos]])
    
    # Re-create the multi-index
    series.index = pd.MultiIndex.from_arrays(vals, names=series.index.names)
    
    print series
    # index  other_index
    # str1   1              s1
    # str2   2              s2
    # dtype: object
    

    【讨论】:

    • 不幸的是,我需要能够匹配任何特定字符
    • 然后在“Julien Spronck”的代码中动态分配“@”。 x 是你的符号: series.index = series.index.map(lambda v: v.replace(x, ''))
    • @Rambatino 我更改了此解决方案以使用多索引...如果有帮助请告诉我
    • 非常感谢 :)
    猜你喜欢
    • 2013-02-19
    • 2012-09-19
    • 2012-05-16
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多