1
def region_df(df):
    if (df["Region New"] == "OTHER" and df[['COUNTRY NAME']].notnull().all()):
        return df["REGION NEWER"]
    elif (df["Region New"] == "OTHER" and (df["national Code"].str[:2] == "4A"  or df["national Code"][:1]== "3") ):
        return 'NOT REEQUIRED'
    else :
        return df["Region New"]`

I am having issues in slicing the column information in a function.

If I use df["national Code"].str[:2] == "4A" , I get the results but when I use the same in a function as below. It gives me the error. Can anyone help?

Error: AttributeError: 'str' object has no attribute 'str'

Expecting to get "not required" when the df["national Code"] has 4A or 3 in the beginning

yashaswi k
  • 668
  • 7
  • 17
aryastark
  • 181
  • 1
  • 4

1 Answers1

1

Taken sample input

import pandas as pd

def region_df(df):
    if ((df["Region New"] == "OTHER") & df['COUNTRY NAME'].notnull()).all():
        return df["REGION NEWER"]
    elif ((df["Region New"] == "OTHER") & ((df["national Code"].str[:2] == "4A") | (df["national Code"].str[:1] == "3"))).any():
        return 'NOT REQUIRED'
    else:
        return df["Region New"]


df = pd.DataFrame({"national Code": ["4ABC", "3678", "5XYZ"],
                   "Region New": ["OTHER", "ABC", "XYZ"],
                   "COUNTRY NAME": ["COUNTRY1", "COUNTRY2", "COUNTRY3"],
                   })

result = region_df(df)
print(result)

output

NOT REQUIRED
yashaswi k
  • 668
  • 7
  • 17