英文:
AttributeError: 'str' object has no attribute 'str' when used in a user defined function
问题
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.
英文:
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
答案1
得分: 1
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)
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论