0

I want to replace a part of string in a dataframe. For example,

df =
index                    group
2019-02-01 09:30:07     8157_S1
2019-02-01 09:30:23    S_1.M_01
2019-02-01 09:30:38    S_1.M_02
2019-02-01 09:32:11    S_1.M_08
2019-02-01 09:32:27    S_1.M_12
2019-02-01 09:32:42    S_1.M_11
2019-02-01 09:32:57    S_1.M_10
2019-02-01 09:33:13    S_1.M_09
2019-02-01 09:33:30     8157_S2
2019-02-01 09:33:47    S_2.M_13

I want to remove "8157_" and "S_1." and "S_2.". My present code is

df['group'] = df['group'].replace("8157_", "") 
df['group'] = df['group'].replace("S_1.","") 

There was no change in the output.

But my expected output is

df =
index                    group
2019-02-01 09:30:07    S1
2019-02-01 09:30:23    M_01
2019-02-01 09:30:38    M_02
2019-02-01 09:32:11    M_08
2019-02-01 09:32:27    M_12
2019-02-01 09:32:42    M_11
2019-02-01 09:32:57    M_10
2019-02-01 09:33:13    M_09
2019-02-01 09:33:30     S2
2019-02-01 09:33:47    M_13
2
  • 3
    use df['group'].str.replace Commented Jan 22, 2020 at 0:53
  • 2
    Or add regex=True to your replace Commented Jan 22, 2020 at 0:53

1 Answer 1

1

Using pandas.Series.str.replace:

df['group'] = df['group'].str.replace("S_[12]\.|8157_","") 
print(df)

Output:

                 index group
0  2019-02-01 09:30:07    S1
1  2019-02-01 09:30:23  M_01
2  2019-02-01 09:30:38  M_02
3  2019-02-01 09:32:11  M_08
4  2019-02-01 09:32:27  M_12
5  2019-02-01 09:32:42  M_11
6  2019-02-01 09:32:57  M_10
7  2019-02-01 09:33:13  M_09
8  2019-02-01 09:33:30    S2
9  2019-02-01 09:33:47  M_13
Sign up to request clarification or add additional context in comments.

2 Comments

Just great! your one line code did exactly what I wanted. In between, S_[12]\. means what?
It means replace S_{1 or 2}\.. Note the backslash for \.; without it, . is interpreted as any char which is not in your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.