I need help for my problem. I try replace "pe60" with "pe61" in column "level_2" if have ("pe60" in column "level_2" and "b" in column "level_1") and the same replace "pe70" with "pe71" in column "level_2" if have ("pe70" in column "level_2" and "b" in column "level_1"). my try but not work is:
import pandas as pd
data = {'Name': ['Tom','nick','krish','jack','bob'],
'level_1': ['a', 'b', 'a', 'b','a'],
'level_2': ['pe60', 'pe70', 'pe71', 'pe60','pe60'],
'level_3': [-2, -1, 4, 6,-4],
}
df = pd.DataFrame(data)
print(df)
def f(row):
if (row['level_2'] == 'pe60') & (row['level_1'] == 'b'):
val = (row['level_2'] == 'pe61')
elif (row['level_2'] == 'pe70') & (row['level_1'] == 'b'):
val = (row['level_2'] == 'pe71')
else:
val = row['level_2']
return val
df['level_2'] = df.apply(f, axis=1)
print(df)
my solution must be:
data_sol = {'Name': ['Tom', 'nick', 'krish', 'jack','bob'],
'level_1': ['a', 'b', 'a', 'b','a'],
'level_2': ['pe60', 'pe71', 'pe71', 'pe61','pe60'],
'level_3': [-2, -1, 4, 6,-4],
}
df_solution = pd.DataFrame(data_sol)
print(df_solution)
how can solve my problem ?
You were really close! You want to return the value, not test for equality:
def f(row):
if (row['level_2'] == 'pe60') & (row['level_1'] == 'b'):
val = 'pe61'
elif (row['level_2'] == 'pe70') & (row['level_1'] == 'b'):
val = 'pe71'
else:
val = row['level_2']
return val
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With