0

I'm having issues with a loop that I want to: a. see if a value in a DF row is greater than a value from a list b. if it is, concatenate the variable name and the value from the list as a string c. if it's not, pass until the loop conditions are met.

This is what I've tried.

import pandas as pd
import numpy as np

df = {'level': ['21', '22', '23', '24', '25', '26', '27', '28', '29', '30']
     , 'variable':'age'}

df = pd.DataFrame.from_dict(df)

knots = [0, 25]
df.assign(key = np.nan)
for knot in knots:
    if df['key'].items == np.nan:
        if df['level'].astype('int') > knot:
            df['key'] = df['variable']+"_"+knot.astype('str')
    else:
         pass
else:
     pass

However, this only yields the key column to have NaN values. I'm not sure why it's not placing the concatenation.

1
  • NaN/np.nan is special; it's not equal to anything, not even itself. You need to use np.isnan to test for it. I don't have enough experience to say how this works with pandas dataframes, so this isn't an answer, but the important part here is that df['key'].items == np.nan is guaranteed to be False. Commented Sep 13, 2019 at 13:10

1 Answer 1

1

You can do something like this inside the for loop. No need of any if conditions:

df.loc[df['level'].astype('int') > 25, 'key'] = df.loc[df['level'].astype('int') > 25, 'variable'] + '_' + df.loc[df['level'].astype('int') > 25, 'level']
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @abhilb. However, the last know overwrites the previous knot. Somehow, I have to look to see if a value is None or nan, before putting in the above.
check that last comment. this works. I just have to rearrange the knots values in ascending order. Thanks.
happy to help :)

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.