2

I have a dataframe as below. I am trying to check if there is 0 or 1 in the vector column, if yes, add 10 to the vector and divide by adding 2 to the vector otherwise keep the same vector.

df = pd.DataFrame({'user': ['user 1', 'user 2', 'user 3'],
                   'vector': [[0.01, 0.07, 0.0, 0.14, 0.0, 0.55, 0.11],
                              [0.12, 0.27, 0.1, 0.14, 0.1, 0.09, 0.19],
                              [0.58, 0.07, 0.02, 0.14, 0.04, 0.06, 1]]})
df

Output:

user    vector
0   user 1  [0.01, 0.07, 0.0, 0.14, 0.0, 0.55, 0.11]
1   user 2  [0.12, 0.27, 0.1, 0.14, 0.1, 0.09, 0.19]
2   user 3  [0.58, 0.07, 0.02, 0.14, 0.04, 0.06, 1]

I used the following code:

  df['vector']=df.apply(lambda x: x['vector']+10/(x['vector']+2) if x['vector']==0|1  else x['vector'], axis=1)

But the Output:

user    vector
0   user 1  [0.01, 0.07, 0.0, 0.14, 0.0, 0.55, 0.11]
1   user 2  [0.12, 0.27, 0.1, 0.14, 0.1, 0.09, 0.19]
2   user 3  [0.58, 0.07, 0.02, 0.14, 0.04, 0.06, 1]

The expected output:

expected output

4
  • 1
    0+10/(0*2) is not equal to 5, did you mean 0+10/(0+2)? Commented Dec 28, 2022 at 19:37
  • 1
    yes, sorry for that, i mean df.apply(lambda x: x['vector']+10/(x['vector']+2) if x['vector']==0|1 else x['vector'], axis=1) Commented Dec 28, 2022 at 19:40
  • Then 1 should give 4.333? Commented Dec 28, 2022 at 19:41
  • 1
    yes, that right Commented Dec 28, 2022 at 19:49

1 Answer 1

4

Use a list comprehension (faster than apply):

df['vector'] = [[x+10/(x+2) if x in [0,1] else x for x in v] for v in df['vector']]

Output:

     user                                                   vector
0  user 1                 [0.01, 0.07, 5.0, 0.14, 5.0, 0.55, 0.11]
1  user 2                 [0.12, 0.27, 0.1, 0.14, 0.1, 0.09, 0.19]
2  user 3  [0.58, 0.07, 0.02, 0.14, 0.04, 0.06, 4.333333333333334]
Sign up to request clarification or add additional context in comments.

3 Comments

@alxander21 sure, what would you want to do exactly?
@ mozway I want to normalize or clip the values that meet condition (0 or 1), so these values don't exceed one!
@alxander21, should negative values (e.g. -0.2) be also clipped to 0 ?

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.