0

This is python code for dataframe

from pandas import DataFrame
import pandas as pd
names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin'],
'Status':['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin'],
"charge":[10,11,12,13,14]}
df = pd.DataFrame(names)

This is the lambda function for generating output

df['Status'] = df['First_name'].apply(lambda x: [df["charge"]] if x == 'Ria' else 'Not Found')
print(df)

The output generated is this:

df['Status'] = df['First_name'].apply(lambda x: [df["charge"]] if x == 'Ria' else 'Not Found')
print(df)

The output is

  First_name                  Status  charge
0      Hanah               Not Found      10
1        Ria  [[10, 11, 12, 13, 14]]      11
2        Jay               Not Found      12
3      Bholu               Not Found      13
4     Sachin               Not Found      14

But I want to generate the output

  First_name                  Status  charge
0      Hanah               Not Found      10
1        Ria                      11      11
2        Jay               Not Found      12
3      Bholu               Not Found      13
4     Sachin               Not Found      14

So as in second row it is Ria so I have to fetch the result of charge(column) in second row and put it in status(column)

GALAXY A50
  • 29
  • 7

2 Answers2

0

lambda can be used in the place of def function First_name Status charge 0 Hanah Not Found 10 1 Ria 11 11 2 Jay Not Found 12 3 Bholu Not Found 13 4 Sachin Not Found 14 this table can eaisly be conn using def

0

if you want use apply and lambda func, apply lambda func to all dataframe with axis=1

df['Status'] = df.apply(lambda x: x['charge'] if x['First_name'] == 'Ria' else 'Not Found', axis=1)

df

    First_name  Status  charge
0   Hanah       Not Found   10
1   Ria         11          11
2   Jay         Not Found   12
3   Bholu       Not Found   13
4   Sachin      Not Found   14

but we can use mask instead apply

cond1 = df['First_name'].ne('Ria')
df.assign(Status=df['charge'].mask(cond1, 'Not Found'))

result:

    First_name  Status  charge
0   Hanah       Not Found   10
1   Ria         11          11
2   Jay         Not Found   12
3   Bholu       Not Found   13
4   Sachin      Not Found   14
Panda Kim
  • 6,246
  • 2
  • 12