<jupyter_start><jupyter_text>`Apply`, `Map`, and `Applymap` in Pandas<jupyter_code>import pandas as pd
df = pd.DataFrame({
    "Region":['North','West','East','South','North','West','East','South'],
    "Team":['One','One','One','One','Two','Two','Two','Two'],
    "Squad":['A','B','C','D','E','F','G','H'],
    "Revenue":[7500,5500,2750,6400,2300,3750,1900,575],
    "Cost":[5200,5100,4400,5300,1250,1300,2100,50]
})
df.head()<jupyter_output><empty_output><jupyter_text>-------  ApplyUse `apply()` to alter values along an axis in your **dataframe** or in a **series** by applying a function. + make sure to put axis=1 if you are comparing values by columns<jupyter_code>df['Profit'] = df.apply(lambda x: 'Profit' if x['Revenue'] > x['Cost'] else 'Loss', axis=1)
df<jupyter_output><empty_output><jupyter_text>----  MapUse `map` to substitute each value in a **series**, using either a function, dictionary, or series.<jupyter_code>team_color = {
    'One': 'Red',
    'Two': 'Blue'
}
df['Team Color'] = df['Team'].map(team_color)
df<jupyter_output><empty_output><jupyter_text>---------  ApplymapUse `applymap()` to apply a function to each element in your **dataframe**<jupyter_code>df.applymap(lambda x : len(str(x)))

# in this case every elements character length is calculated (both Numeric and String values)<jupyter_output><empty_output><jupyter_text>------  If all else fails, use a `for` loop.  We want to find the Revenue % of each Team per Region.<jupyter_code>df.head()
# Total Revenue for Row Index 0's region (North)
df[df['Region'] == df.loc[0, 'Region']]['Revenue'].sum()
revenue_percent = []

for i in range(0, len(df)):
    total_revenue_per_region = df[df['Region'] == df.loc[i, 'Region']]['Revenue'].sum() 
    rev = df['Revenue'][i] / total_revenue_per_region
    revenue_percent.append(rev)
df['Revenue Share of Region'] = revenue_percent
df.sort_values(by='Region')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19708029197080293, 'fraction_numerical': 0.03441084462982273, 'mean_word_length': 6.055147058823529, 'pattern_counts': {'":': 5, '<': 21, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '166996', 'license': 'MIT', 'n_tokens_mistral': 734, 'n_tokens_neox': 678, 'n_words': 160, 'path': 'Pandas - Advanced Pandas/02.Advanced Calculations/02-05-map_apply_functions.ipynb', 'repo_name': 'ptyadana/probability-and-statistics-for-business-and-data-science', 'size': '1918'}