This is the question I asked before, But I explained it in the wrong way, So I am going to open a new question again.Appreciate your help and time !
Data Input:
df=pd.DataFrame({'variable':["A","A","B","B","C","D","E","E","E","F","F","G"],'weight':[2,2,0,0,1,3,3,1,5,0,0,4]})
df
Out[447]:
variable weight
0 A 2
1 A 2
2 B 0
3 B 0
4 C 1
5 D 3
6 E 3
7 E 1# If value more than 2 , out put should be 0
8 E 5
9 F 0
10 F 0
11 G 4
Expected Output :
df
Out[449]:
variable weight NEW
0 A 2 1
1 A 2 1
2 B 0 1
3 B 0 1
4 C 1 1
5 D 3 ERROR
6 E 3 ERROR
7 E 1 1
8 E 5 1
9 F 0 1
10 F 0 1
11 G 4 ERROR
My approach as of now (ugly..):
l1=[]
for i in df.variable.unique():
temp=df.loc[df.variable==i]
l2 = []
for j in range(len(temp)):
print(i,j)
if temp.iloc[j,1]<=2 :
l2.append(1)
elif temp.iloc[j,1]>2 and j==0:
l2.append('ERROR')
elif temp.iloc[j,1]>2 and j > 0 :
if l2[j - 1] == 1:
l2.append(1)
else:
l2.append(0)
print(l2)
l1.extend(l2)
df['NEW']=l1
My question here:
1st. If I want to use groupby , how can I make per-calculated result involved in the future calculation , in order to get the NEW column here.
2nd. Is there any pandas function like .Last.value in R ?
I will explain the condition here :
1.If the value of weight less than 2 always should be 1
2.If the first value of weight higher than 2 it should be return ERROR
3.If the previous one getting 'ERROR' and weight value current row is more than 2 it will return 0
And kindly change The Input to :
df=pd.DataFrame({'variable':["A","A","B","B","C","D","E","E","E","F","F","G"],'weight':[2,2,0,0,1,3,3,9,5,0,0,4]})