alxander21
alxander21

Reputation: 171

Pandas .apply with conditional if in one column

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

Upvotes: 2

Views: 120

Answers (1)

mozway
mozway

Reputation: 260300

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]

Upvotes: 4

Related Questions