0

So, I have this col which I have saved as a series(els):


1           B S C
2           B S C
6           B S C
7         B S C L
8         B S C L
          ...    
2522    B S* C Sa
2523    B S* C Sa
2524    B S* C Sa
2526        B S C
2529        B S C

And I want to create a list of binary values depending upon the letter 'B' residing in els. My most effective attempt was:

ima_b = []

for line in els.iteritems():
    if 'B' in line:
        ima_b.append(1)
    else:
        ima_b.append(0)
print(ima_b)

Which returns:


[0,0,0,0,0,...0,0,0,0,0]

I've tried searching for solutions and playing with the code for 3 days (over 8 hours). I just cannot figure out what I am doing wrong here and I am about to lose my mind. Examples of things I've tried: .loc, converting to different types and reformatting, converting back. When I tried reformatting, it would cut out some of the data.

My end goal with this list is to create a True/False column for if 'B' is located in els and graph it.

  • 1
    `ima_b = els.str.contains('B', regex=False).tolist()` – ouroboros1 Jun 01 '22 at 20:28
  • Incidentally, the problem with your `iteritems` solution (surely, slower) is that you are iterating over a (index, value) tuples. This means you're testing: `'B' in (1, 'B S C')`, etc., whereas you want to test `'B' in 'B S C'` etc. So, to make your code work, use `if 'B' in line[1]:`. – ouroboros1 Jun 01 '22 at 20:38
  • 1
    Thank you so much! I'm pretty new to coding and I'm still not super familiar with all the different methods and attributes. I even tried googling the different types + methods and I must have missed contains. I feel like the dumbest person on the planet. I tried both codes and only the first worked for me. I tried adjusting my for loop again but with no success. – Aidoneus M Jun 02 '22 at 19:16
  • You're welcome. Not sure why the 2nd option isn't working for you. It should. It's just `if 'B' in line[1]:` instead of your `if 'B' in line:`. Anyway, that was just to explain the procedural error. A simple `for x in els:` loop would do, or have a look at [if/else in a list comprehension](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension). General tip: if you get unexpected results, include some print statements (e.g. `print(line)` before your `if` line), to see what you're dealing with. Good luck with practicing! – ouroboros1 Jun 02 '22 at 20:03

0 Answers0