0

I want to extra the first portion of column (B) based on the value of another column (A) minus 1 to get an output. Eg, if column A is 4 than I want the first 3 characters of column B.

Any suggestions? Greatly appreciated!

+---+---------------+------+
| A |       B       | Out  |
+---+---------------+------+
| 4 |  CTAAT        |  CTA |
| 3 |  GKAEI        |  GK  |
+---+---------------+------+

ie first 3 letters of column B in row 1, the fist 2 letters of column B in row 2.

My current approach that isn't working:

df['output']= df.B.str[0:(df[A]-1)]

1 Answer 1

2

You can use pandas.apply:

df['output']=df.apply(lambda x: x['B'][:x['A']-1], axis=1)
print(df)

A      B         output
4      CTAAT     CTA
3      GKAEI     GK
Sign up to request clarification or add additional context in comments.

5 Comments

This is giving me the error:TypeError: slice indices must be integers or None or have an index method
Okay, I see what you are saying. I did not have the 'output' column created yet, but was relying on the column to be created with the line of code. Thanks! That did work for me.
Nevermind, I am still having issues with getting the error I listed above. It did give me the correct output once, but not it is giving me the error again. Any insights to why I wouldn't be able to reference the column? dtypes lists it as an int.
You are saying that you got the right output and also getting the error ? Could you explain what's the issue
Yes, sorry for the confusion. I am operating in Jupyter and launch the cell, which gave the error "TypeError: slice indices must be integers or None or have an index method". I went back and added an empty 'output' column to the df prior to the pandas.apply function. Then, when I reran the cell with pandas.apply, it worked. But, the same error appears as before whenever I run the entire script from the beginning.

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.