【问题标题】:How use the apply function to one dataframe which has two dataframes passing as parameters?如何将 apply 函数用于一个具有两个作为参数传递的数据帧的数据帧?
【发布时间】:2022-10-13 18:29:12
【问题描述】:

我有两个数据框df 和df_census_final。 df 可以下载数据 here 和 df_census_final 可以下载 here 并使用以下命令创建:

import pandas as pd
df = pd.read_csv('population_data.csv')
df_census_final = pd.read_csv('census_data.csv')

df_census_final 是按各个年龄组对人口的逐年估计,是一个查找数据框以获取特定值,而df 是将应用计算的实际数据框和按年龄组划分的人口15-19.

我有两个函数,下面是第一个函数function_check_age_19 用于底部函数split_population_18_19:

def function_check_age_19(df,df_census_final):
    """
    If the sex, year, and age are equal to the values in the function, then return the population
    multiplied by the estimated proportion.
    
    :param df: the dataframe that contains the population data
    :param df_census_final: a dataframe with the following columns:
    :return: the population multiplied by the estimated proportion.
    """
    if df['Sex'] == 'Male' and df['Year'] == 2019 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Male Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2019)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Female' and df['Year'] == 2019 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Female Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2019)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Male' and df['Year'] == 2020 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Male Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2020)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Female' and df['Year'] == 2020 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Female Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2020)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Male' and df['Year'] == 2021 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Male Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2021)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Female' and df['Year'] == 2021 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Female Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2021)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Male' and df['Year'] == 2022 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Male Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2022)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Female' and df['Year'] == 2022 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Female Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2022)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Male' and df['Year'] == 2023 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Male Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2022)].values)/100
        return df['population']*estimated_proportion
    elif df['Sex'] == 'Female' and df['Year'] == 2023 and df['Age'] == '15-19':
        estimated_proportion =(df_census_final['Female Pop %'].loc[(df_census_final['GROUP'] == '19') & (df_census_final['Year'] == 2022)].values)/100
        return df['population']*estimated_proportion
    else: 
        return df['population'] 

def split_population_18_19(df):
    """
    It takes a dataframe, creates two new columns, one for 18 year olds and one for 19 year olds, then
    adds them together and subtracts them from the total population
    
    :param df: The dataframe that you want to split the population for
    :return: A dataframe with the columns:
    """
    try:
        df['population_18'] = df.apply(lambda row: function_check_age_18(row), axis=1)
        df['population_19'] = df.apply(lambda row: function_check_age_19(row), axis=1)
        df.loc[df['Age'] != '15-19','population_18'] = 0
        df.loc[df['Age'] != '15-19','population_19'] = 0
        df['total_population_18'] = df['population_18'] + df['population_19']
        df['population'] =df['population'] - df['total_population_18']
        df['total_population_18'] = df['total_population_18'].shift(1)
        df['total_population_18'] = df['total_population_18'].fillna(0.0)
        df['population'] = df['total_population_18'] + df['population']
        df.drop(['month','population_18','population_19','total_population_18'],axis=1,inplace=True)
        return df
    except Exception as e:
        print(f"Exception on estimating 18 19 year old population with the error: {e}")

第一个函数有两个传递给它的数据帧,df 和 df_census_final,但第二个函数只有一个。在第二个函数中使用.apply时如下图:

df['population_19'] = df.apply(lambda row: function_check_age_19(row), axis=1)

我得到一个非类型返回。即(我只是想影响dfelement-wise) 什么是使用。申请函数或其他任何东西都可以将两个数据帧都传递给函数?

我正在重构一些硬编码值,如下所示:

def function_check_age_19(df):
    """
    This function is checking the population of the age group 15-19 for the years 
    2019, 2020, 2021, and 2022 then mapping the proportion for 19 year olds for each Sex
    """
    if df['Sex'] == 'Male' and df['Year'] == 2019 and df['Age'] == '15-19':
        return df['population']*(19.851399/100)
    elif df['Sex'] == 'Female' and df['Year'] == 2019 and df['Age'] == '15-19':
        return df['population']*(20.088195/100)
    elif df['Sex'] == 'Male' and df['Year'] == 2020 and df['Age'] == '15-19':
        return df['population']*(19.492101/100)
    elif df['Sex'] == 'Female' and df['Year'] == 2020 and df['Age'] == '15-19':
        return df['population']*(19.745797/100)
    elif df['Sex'] == 'Male' and df['Year'] == 2021 and df['Age'] == '15-19':
        return df['population']*(19.489112/100)
    elif df['Sex'] == 'Female' and df['Year'] == 2021 and df['Age'] == '15-19':
        return df['population']*(19.621289/100)
    elif df['Sex'] == 'Male' and df['Year'] == 2022 and df['Age'] == '15-19':
        return df['population']*(19.442557/100)
    elif df['Sex'] == 'Female' and df['Year'] == 2022 and df['Age'] == '15-19':
        return df['population']*(19.534988/100)
    else: 
        return df['population']

【问题讨论】:

  • 看起来它在这里过于复杂了。做一个 .groupby() 然后计算你需要的东西不是很有意义吗?
  • 如果您共享 df 的样本以及您希望输出的样子会有所帮助
  • @chitown88 你是说使用 .groupby 和 lambda 吗?本质上,df_census_final 是人口比例的查找表。现在将尝试创建示例 df。但是使用 function_check_age_19(row),当我只通过一个数据帧时,它就起作用了,
  • 不,我说的是数据框本身的 groupby。除非我不理解这个问题。是的,看看 df 的样子和你想要做什么会很有帮助。
  • @chitown88 我已经用数据源更新了问题以提供帮助

标签: python pandas dataframe lambda apply


【解决方案1】:

好的,我想我明白您要做什么。我将如何做到这一点,我只需将百分比合并'Sex' 和'Year'。然后只需拉出GROUP 18 和 19 并乘以列以获得这些的人口。

import pandas as pd
import numpy as np

df = pd.read_csv('https://raw.githubusercontent.com/maz2198/data_1/main/population_data.csv')
df['Year'] = pd.to_datetime(df['month of estimation']).dt.year
df_15_19 = df[df['Age'] == '15-19']

df_census_final = pd.read_csv('https://raw.githubusercontent.com/maz2198/data_1/main/census_data.csv')

df_list = []
ages = [18, 19]
for age in ages:
    df_census_age = df_census_final[df_census_final['GROUP'] == age]
    df_age = df_15_19.merge(df_census_age, how='right', on = ['Year'])

    df_age['pop'] = np.where(df_age['Sex'] == 'Female', df_age['Female Pop %'], df_age['Male Pop %'])
    df_age['population_calc'] = df_age['population'] * (df_age['pop']/100)
    
    df_list.append(df_age)
    
final_df = pd.concat(df_list, axis=0)

输出:

print(final_df[['district', 'Sex', 'Year', 'GROUP', 'population_calc']])
                                          district  ... population_calc
0      MP - Ehlanzeni District Municipality (DC32)  ...    16113.420033
1      MP - Ehlanzeni District Municipality (DC32)  ...    15696.491268
2     EC - Alfred Nzo District Municipality (DC44)  ...     8754.005492
3     EC - Alfred Nzo District Municipality (DC44)  ...     8220.401384
4       EC - Amathole District Municipality (DC12)  ...     6713.988338
                                           ...  ...             ...
3947     WC - Overberg District Municipality (DC3)  ...     2189.536237
3948   WC - West Coast District Municipality (DC1)  ...     3601.165452
3949   WC - West Coast District Municipality (DC1)  ...     3579.662585
3950                        WC- Garden Route (DC4)  ...     5120.187331
3951                        WC- Garden Route (DC4)  ...     4867.683393

[7904 rows x 5 columns]

视觉的:

import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn plotting aesthetics
sns.set(style='white')

#create grouped bar chart
sns.barplot(x='Year', y='population_calc', hue='Sex', data=final_df,
            palette=['#DFA1C1', '#3279BB']) 
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.ylabel('Population')

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2020-06-16
    • 2019-03-05
    • 1970-01-01
    • 2020-09-18
    • 2021-03-12
    • 2016-12-04
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多