0

I need to add value to string without making "TRC+TRC" cells. So if it already contains TRC -> add nothing. How to do it?

for i in range(len(df)):
  d = str(df['description'][i]).lower()
  if df['segment'][i] == 'shopping':
    if any(TRC in d for TRC in TRC):
      if (df['landsize'][i] > 9000):
        df['class'][i] = (f"{df['class'][i]} + TRC")
        continue

and what are other variants to do this thing?

df['class'][i] = (f"{df['class'][i]} + TRC")
2
  • Can TRC be in the middle of the string or will it always be at the start or end? Commented Aug 21, 2019 at 13:05
  • i have multiple classes like TRC, so it may add multiple times and in random positions, thanks Commented Aug 21, 2019 at 13:09

2 Answers 2

1

I believe this is what you're looking for, definitely avoid loops in pandas in anyway possible. Hope that this is what you meant :)

df['description'] = df['description'].str.lower()

df.loc[(df['segment'] == 'shopping')
   &(~df['description'].str.contains('trc')) 
   & (df['landsize'] > 9000)
   , 'class'] += "TRC"
Sign up to request clarification or add additional context in comments.

4 Comments

i have both variants of code: with loops and with loc. But @Benoit Drogou wrote with iloc for some reason :) but with loc i have another troubles, so i'm trying to do this as loop now
what does ~ mean?
Maybe try to solve your loc problem? It's the cleaner way to approach it in my opinion,
~ means not, so it checks that description doesn't contain trc
1

Loops are not pythonic at all, the more you are avoiding them the better, faster and more efficient your code is.

df.loc[ (df['segment']=='shopping')
       & (df['landsize']>9000)
       & (~df['class'].str.contains(pat='TRC', na=False))
       , 'class'] += 'TRC'

I maybe misunderstood your issue

2 Comments

I think they meant that df['class'] cells must be appended 'TRC' under the conditions, not make it 'TRC'.
sure, then += works for dataframe as well, I updated the answer

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.