I would like to add the value online by level. If I find a value other than 0 in row 0 for column 1 the whole row must contain the value differents, how explained in my example. I'm not sure how to get around the problem. If you have any ideas
Input :
import pandas as pd
data = {
'Level1 - Code' : [0, 0, 0, 2],
'Level2 - Code' : [0, 1, 0, 0],
'Level3 - Code' : [2, 0, 0, 0],
'Level4 - Code' : [0, 0, 0, 0]
}
df = pd.DataFrame(data)
print(df)
Output :
data = {
'Level1 - Code' : [0, 0, 0, 2],
'Level2 - Code' : [0, 1, 0, 2],
'Level3 - Code' : [2, 1, 0, 2],
'Level4 - Code' : [2, 1, 0, 2]
}
df_output = pd.DataFrame(data)
print(df_output)
I try to do that whit this :
def f(x):
lst_value = list(x.values)
if 2 in lst_value:
index = lst_value.index(2)
lst_value[index:] = [2] * len(lst_value[index:])
return pd.Series(lst_value, index = list(x.index))
df.apply(lambda x: f(x), axis = 1)
Thank you,
CodePudding user response:
You could use cummax
:
df_output = df.cummax(axis=1)
output:
Level1 - Code Level2 - Code Level3 - Code Level4 - Code
0 0 0 2 2
1 0 1 1 1
2 0 0 0 0
3 2 2 2 2