1

I have this value 10-X-002 in a column and I want to extract only the X-002 to be in a new column.

So far what I have tried was this:

mask = df["eq_id"].str.count('-').gt(0)
splitted = df["eq_id"].str.split("-")
df.loc[mask, "eg_number"] = splitted[mask].str[-1]

but the script resulted only the 002 is in the new column, what should I do to get X-002 value in the new column?

Thankyou.

1
  • You should just try to split only once. change it to splitted = df["eq_id"].str.split("-",1) Commented Oct 5, 2020 at 3:14

4 Answers 4

2

add first + and '-' with last element

mask = df["eq_id"].str.count('-').gt(0)
splitted = df["eq_id"].str.split("-")
df.loc[mask, "eg_number"] = splitted[mask].str[1]+'-' +splitted[mask].str[-1]

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

if you can plz upvote my answer @nomnom3214
1

The simplest thing is to only change one line in your code which is totally fine.

change this splitted = df["eq_id"].str.split("-")

into this splitted = df["eq_id"].str.split("-", 1)

which means you want only one split based on '-' starting from the left.

Leave the rest of your code unchanged, it should do the job

Comments

0

If you know the index location of the string, then you can do this:

mask = df["eq_id"].split('-')[1]+'-'+df["eq_id"].split('-')[-1]
df.loc[mask, "eg_number"] = mask

Split them by '-' sign and recombine those back, and just assign back to that specific column

Comments

0

Try

df["eq_id"].replace('10-','')

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.