Conditional statements on Panda Dataframes using Lambdas

I'm stuck at a simple point. I am trying to set a column in a Panda dataframe that only increases the age for men (0), but for some reason I cannot iterate over the Dataframe (it only repeats the first result, which is 22).

Here is my code:

new_tab['menage'] = new_tab.Gender.apply(
        lambda x: new_tab.iloc[:,1] if x==0 
        else 0)

    Original Age    Gender  menage
0   22.0    0   22.0
1   38.0    1   0.0
2   26.0    1   0.0
3   35.0    1   0.0
4   35.0    0   22.0

I specifically try to do this for lambda, recognizing the existence of other alternatives.

I am sure that this is something really direct, but new to coding, is currently outside of me.

Any help would be brilliant.

thank

+4
source share
2 answers

, new_tab.iloc[:,1] lambda ( , ). , , apply.

1
mask

v = df['Original Age'].mask(df['Gender'].astype(bool)).fillna(0)
v

0    22.0
1     0.0
2     0.0
3     0.0
4    35.0
Name: Original Age, dtype: float64

df['menage'] = v

2
np.where

np.where(df['Gender'], 0, df['Original Age'])

0    22.0
1     0.0
2     0.0
3     0.0
4    35.0
Name: Original Age, dtype: float64

3
apply apply df, , .

df.apply(lambda r: r['Original Age'] if r['Gender'] == 0 else 0, axis=1)

0    22.0
1     0.0
2     0.0
3     0.0
4    35.0
dtype: float64
0

- assign pandas , query boolean indexing:

df.assign(menage = df.query('Gender == 0')['Original Age']).fillna(0)

df.assign(menange = df.loc[df['Gender'] == 0, 'Original Age']).fillna(0)

:

   Original Age  Gender  menage
0          22.0       0    22.0
1          38.0       1     0.0
2          26.0       1     0.0
3          35.0       1     0.0
4          35.0       0    35.0
0

Source: https://habr.com/ru/post/1691050/


All Articles