2016-02-12 180 views
0

我試圖在熊貓系列內的索引中進行字符串替換。但是,目前它不匹配或查找子字符串並將其替換爲給定值。使用正則表達式匹配替換索引值

我目前的系列:

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': {'@': ''}}) 

但是,它似乎並不匹配字符串,返回初始系列。我錯過了什麼,如何達到預期的結果?

我的熊貓版本目前爲0.15。

P.S.我也曾嘗試:

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

UPDATE

一些答案在未來解決的具體問題,但我需要一個更一般的情況。因此,如果該系列是:

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

如何將適用同樣的操作這裏的指數?這對第一項措施和其他措施都有效?

回答

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 
+0

我需要爲了能夠匹配任何特定字符,不幸 – Rambatino

+0

然後動態分配'Julien Spronck'的代碼中的'@' 。 x是你的符號:series.index = series.index.map(lambda v:v.replace(x,'')) – RandomHash

+0

@Rambatino我改變了這個解決方案,使用多索引...讓我知道它是否有幫助 –