Insert a value into a column by a condition Python

Question:

I can’t figure out how to insert a value according to the condition in another column. It is necessary to insert the value from the second file according to the condition, the beginning is the value "01", and the end is the value "01"-1. The beginning always begins with "01".
Examples of input data:

df1 = pd.DataFrame({
'N1': ['01', '02','03','01','02','01','02','03','04'],
'N2':['', '','','','','','','','']})
df2 = pd.DataFrame({
'N1': [ 'PALA A','PALA B','PALA C']})

Result:

result = pd.DataFrame({
'N1': ['01', '02','03','01','02','01','02','03','04'],
'N2':['PALA A', 'PALA A','PALA A','PALA B','PALA B','PALA C','PALA C','PALA C','PALA C']})

Desired result on the screenshot, any help or links to similar examples or documentation would be appreciated.

Asked By: Valerie Oputin

||

Answers:

df1['N2'] = df2.loc[(df1['N1'] == '01').cumsum() - 1].set_axis(df1.index, axis=0)

Result:

   N1      N2
0  01  PALA A
1  02  PALA A
2  03  PALA A
3  01  PALA B
4  02  PALA B
5  01  PALA C
6  02  PALA C
7  03  PALA C
8  04  PALA C
Answered By: Vladimir Fokow