0

I have 2 dataframes below: new_df and fail_dict as below.

new_df

   SN   FM  Pass  Fail
0  A1  FM1    10    15
1  A2  FM3    15    20
2  A3  FM2    45    50
3  A4  FM1    25    30
4  A5    P    50     0
5  A6    P    50     0
6  A7  FM2    10    15
7  A8  FM2    20    25
8  A9  FM1    25    30

fail_dict

    FM    Fail_Mode
0  FM1  fail mode 1
1  FM2  fail mode 2
2  FM3  fail mode 3
3  FM4  fail mode 4

What I am trying to do is that:

  1. I made a copy of new_df in final_df
  2. I take first value of FM in new_df (let's say FM1), compare with all values in fail_dict with the condition that 2.a if I find FM1 in fail_dict then append the original values of all 4 columns in new_df to final_df 2.b. If I don't find FM1 in fail_dict then append final_def with the SN info from new_def, FM info from fail_dict and Pass=50 and fail=0.

The code compiles with our error but final_def is exactly same as new_def and does not seem to get appended as intended. Final output that I am looking for should be something like below. What is wrong with the logic/code here? TIA

SN   FM  Pass  Fail
0  A1  FM1    10    15
1  A1  FM2    50    0
2  A1  FM3    50    0
3  A1  FM4    50    0
.
.

for fm in range(len(new_df.FM)):
    for fmlist in range(len(fail_dict.FM)):
        if new_df.FM[fm]==fail_dict.FM[fmlist]:
            final_df.append({'SN':new_df.SN[fm],'FM':new_df.FM[fm],'Pass':new_df.Pass[fm],'Fail':new_df.Fail[fm]},ignore_index=True)
        else:
            final_df.append({'SN':new_df.SN[fm],'FM':fail_dict.FM[fmlist],'Pass':50,'Fail':0},ignore_index=True)
print(final_df)

1 Answers1

-1

DataFrame.append isn't in-place, so you need to reassign back to the dataframe like this: final_df = final_df.append(...

for fm in range(len(new_df.FM)):
    for fmlist in range(len(fail_dict.FM)):
        if new_df.FM[fm]==fail_dict.FM[fmlist]:
            final_df = final_df.append({'SN':new_df.SN[fm],'FM':new_df.FM[fm],'Pass':new_df.Pass[fm],'Fail':new_df.Fail[fm]},ignore_index=True)
        else:
            final_df = final_df.append({'SN':new_df.SN[fm],'FM':fail_dict.FM[fmlist],'Pass':50,'Fail':0},ignore_index=True)
print(final_df)
richardec
  • 14,202
  • 6
  • 23
  • 49