python - 为数学数据插补python创建一个函数
问题描述
我正在执行许多类似的操作,我想编写一个函数,但我什至不知道如何处理这个问题。我正在计算以下系列的 0 数据的值:
- 公式是 2 * 2001 年的值 - 2002 年的值
我目前在Python中一一做:
print(full_data.loc['Croatia', 'fertile_age_pct'])
print(full_data.loc['Croatia', 'working_age_pct'])
print(full_data.loc['Croatia', 'young_age'])
print(full_data.loc['Croatia', 'old_age'])
full_data.replace(to_replace={'fertile_age_pct': {0:(2*46.420061-46.326103)}}, inplace=True)
full_data.replace(to_replace={'working_age_pct': {0:(2*67.038157-66.889212)}}, inplace=True)
full_data.replace(to_replace={'young_age': {0:(2*0.723475-0.715874)}}, inplace=True)
full_data.replace(to_replace={'old_age': {0:(2*0.692245-0.709597)}}, inplace=True)
数据框(full_data):
geo_full year fertile_age_pct working_age_pct young_age old_age
Croatia 2000 0 0 0 0
Croatia 2001 46.420061 67.038157 0.723475 0.692245
Croatia 2002 46.326103 66.889212 0.715874 0.709597
Croatia 2003 46.111822 66.771187 0.706091 0.72444
Croatia 2004 45.929829 66.782133 0.694854 0.735333
Croatia 2005 45.695932 66.742514 0.686534 0.747083
解决方案
所以你试图用你的公式填充 2000 年的 0 值。如果您在 DataFrame 中有任何其他国家/地区,那么它可能会变得混乱。
假设带 0 的年份始终是每个国家/地区的第一年,试试这个:
full_data.set_index('year', inplace=True)
fixed_data = {}
for country, df in full_data.groupby('geo_full')[full_data.columns[1:]]:
if df.iloc[0].sum() == 0:
df.iloc[0] = df.iloc[1] * 2 - df.iloc[0]
fixed_data[country] = df
fixed_data = pd.concat(list(fixed_data.values()), keys=fixed_data.keys(), names=['geo_full'], axis=0)
推荐阅读
- python - Netmiko for Linux - 发送 sudo 密码
- excel - 通过 ODBC (3.0.6) / ADODB 到 MariaDB 10.3.8 的 VBA 连接
- angularjs - Angular js - 控制器方法在使用 ng-enter 时快速连续按 Enter 触发两次
- c# - 具有可变长度和备用列表内容的列表排列
- entity-framework - EF Core + Sqlite 3.24.0 在使用 UPSERT 操作的触发器中引发异常
- meta-tags - 如何使用元标记来解决加载外部脚本的内容安全策略问题
- json - 在 Rest api Request 中创建多个主体
- javascript - Vuetify.js:部署在 Gitlab 上时 v-stepper 中的颜色属性不生效。如何将颜色道具移动到 CSS 类?
- c++ - 计算两个集合之间的交集时出现 set_intersection 错误
- python - 正则表达式用于使用正向前瞻或后视进行增强分配操作