I'm trying to check if a specific "Route" string starts and ends with the same sub-string but I'm getting an error of "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."
if df1["Route"].str[:3] == df1["Route"].str[-3:]:
print("True")
else:
print("False")
I've tried resolving the issue by use of suggested methods mentioned for similar queries in SO but to no avail..
Here's the snippet from the column "Route" that I'm trying to apply this query on: BBIBOMAMD STVBLRTRV AMDDELAMD AMDCCUAMD AMDBOMAMD PNQAMDPNQ DELAMDDEL AMDGOAAMD
You are trying to use a pandas series as the predicate for the if
condition and that is not a valid operation.
Let me show what I mean by that.
df1["Route"].str[:3]
gives
0 BBI
1 STV
2 AMD
3 AMD
4 AMD
5 PNQ
6 DEL
7 AMD
Name: Route, dtype: object
df1["Route"].str[-3:]
which gives:
0 AMD
1 TRV
2 AMD
3 AMD
4 AMD
5 PNQ
6 DEL
7 AMD
Name: Route, dtype: object
So now when you use these two as part of the if
condition python complains that the True value is ambiguous.
I am assuming that you want to print True or False for each row in the 'Route' column. What you can try is the following.
df1['Route'].apply(lambda x: x[:3] == x[-3:])
which will print the following.
0 False
1 False
2 True
3 True
4 True
5 True
6 True
7 True
Name: Route, dtype: bool