-1

I'm struggling with the logic for a dataframe problem. The existing dataframe I have looks like this

SN      BC        2051   2052    2053   2054   ...
113     NO          Y    N         N     
224     NO            
335     NO          Y    N                N
446     NO          Y    N          N     N 
557     NO          N    Y          Y 

I need help with the changing row 224. I need a line of code that will change the value in the BC column from NO to YES if the rest of the row is empty.It seems simple but I am new to pandas, and trying to learn. Ive tried writing .apply and lambdas, but no luck yet. The finished dataframe should look like

SN      BC        2051   2052    2053   2054   ...
113     NO          Y    N         N     
224     YES            
335     NO          Y    N                N
446     NO          Y    N          N     N 
557     NO          N    Y          Y 

Thank you!

  • 1
    Does this answer your question? [Set value for particular cell in pandas DataFrame using index](https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index) – shaik moeed Aug 07 '23 at 12:57
  • Not really, I dont understand how to apply the logic I need through that example. – TheMcFloyd Aug 07 '23 at 13:09

2 Answers2

1

Example

import pandas as pd
data1 = {'SN': [113, 224, 335, 446, 557], 
         'BC': ['NO', 'NO', 'NO', 'NO', 'NO'], 
         '2051': ['Y', None, 'Y', 'Y', 'N'], 
         '2052': ['N', None, 'N', 'N', 'Y'], 
         '2053': ['N', None, 'N', 'N', 'Y'], 
         '2054': [None, None, None, 'N', None]}
df = pd.DataFrame(data1)

df

enter image description here

Code

cond = df.iloc[:, 2:].isna().all(axis=1)
df['BC'] = df['BC'].mask(cond, 'YES')

df:

enter image description here

Panda Kim
  • 6,246
  • 2
  • 12
0

When using apply you can use a ternary operator to set a condition when updating.

import pandas as pd

data = {
    "SN": [113, 224, 335, 446, 557],
    "BC": ["NO", "NO", "NO", "NO", "NO"],
    "2051": ["Y", "", "Y", "Y", "N"],
    "2052": ["N", "", "N", "N", "Y"],
    "2053": ["N", "", "", "N", "Y"],
    "2054": ["", "", "N", "N", "Y"],
}

df = pd.DataFrame(data)
df["BC"] = df.apply(lambda row: "YES" if (row[2:] == "").all() else row["BC"], axis=1)
print(df)

Output

    SN   BC 2051 2052 2053 2054
0  113   NO    Y    N    N
1  224  YES
2  335   NO    Y    N         N
3  446   NO    Y    N    N    N
4  557   NO    N    Y    Y    Y
rochard4u
  • 629
  • 3
  • 17