I have a list of values in a sequence from most important to least important, if it doesn't find a value, it searches for the next one and so on:
import pandas as pd
markets_base = [
'Over/Under 8.5 Goals','First Half Goals 1.5','Over/Under 4.5 Goals','First Half Goals 0.5'
]
markets_df = pd.DataFrame({
'competition': ['a','b','c'],
'market_name': ['First Half Goals 1.5','Over/Under 4.5 Goals','First Half Goals 0.5']
})
for mkt_base in markets_base:
if len(markets_df.loc[markets_df['market_name'] == mkt_base]) > 0:
final_row = markets_df.loc[markets_df['market_name'] == mkt_base].iloc[:1]
break
print(final_row)
Is there a more professional way to the same result or is this the correct model?
CodePudding user response:
A possible solution involves turning your 'market_name' column into categorical as explained in this answer: Custom sorting in pandas dataframe
In your case this would do the trick:
import pandas as pd
markets_df = pd.DataFrame({
'competition': ['a', 'b', 'c', 'd', 'e'],
'market_name': ['First Half Goals 1.5', 'Over/Under 4.5 Goals', 'First Half Goals 0.5', 'Over/Under 8.5 Goals', 'Over/Under 4.5 Goals']
})
markets_base = [
'Over/Under 8.5 Goals', 'First Half Goals 1.5', 'Over/Under 4.5 Goals', 'First Half Goals 0.5'
]
#here's the thing
markets_df["market_name"] = pd.Categorical(
markets_df['market_name'], markets_base)
final_row = markets_df.sort_values("market_name").iloc[:1]
print(final_row)