使用 Panda 的 Apply 计算一个值 - KeyError
Using Panda's Apply to calculate a value - KeyError
我有一个如下所示的 Panda DataFrame:
country year cases population
0 Afghanistan '99 745 19987071
1 Brazil '99 37737 172006362
2 China '99 212258 1272915272
3 Afghanistan '00 2666 20595360
4 Brazil '00 80488 174504898
5 China '00 213766 1280428583
我想添加一个名为 'prevalence' 的新列,即该行的案例除以人口。这行代码有效:
G['prevalence'] = G['cases'] / G['population']
但是,我想使用 Panda 的应用来做同样的事情。这是我正在尝试做的事情:
def get_prev (x, y):
return x / y
def calc_prevalence(G):
assert 'cases' in G.columns and 'population' in G.columns
###
### YOUR CODE HERE
to_return = G.copy()
new_column = to_return.apply(lambda x: get_prev(to_return.population, to_return.cases), axis=1)
to_return['prevalence'] = new_column
return to_return
###
#G_copy = G.copy()
H = calc_prevalence(G)
我得到一个 KeyError: 'prevalence'
知道我做错了什么吗?
只需使用下面的代码即可完成
def func(x):
res = x['cases']/x['population']
return res
df['prevalence'] = df.apply(func, axis=1)
输出
country year cases population prevalence
0 Afghanistan '99 745 19987071 0.000037
1 Brazil '99 37737 172006362 0.000219
2 China '99 212258 1272915272 0.000167
3 Afghanistan '00 2666 20595360 0.000129
4 Brazil '00 80488 174504898 0.000461
5 China '00 213766 1280428583 0.000167
我有一个如下所示的 Panda DataFrame:
country year cases population
0 Afghanistan '99 745 19987071
1 Brazil '99 37737 172006362
2 China '99 212258 1272915272
3 Afghanistan '00 2666 20595360
4 Brazil '00 80488 174504898
5 China '00 213766 1280428583
我想添加一个名为 'prevalence' 的新列,即该行的案例除以人口。这行代码有效:
G['prevalence'] = G['cases'] / G['population']
但是,我想使用 Panda 的应用来做同样的事情。这是我正在尝试做的事情:
def get_prev (x, y):
return x / y
def calc_prevalence(G):
assert 'cases' in G.columns and 'population' in G.columns
###
### YOUR CODE HERE
to_return = G.copy()
new_column = to_return.apply(lambda x: get_prev(to_return.population, to_return.cases), axis=1)
to_return['prevalence'] = new_column
return to_return
###
#G_copy = G.copy()
H = calc_prevalence(G)
我得到一个 KeyError: 'prevalence'
知道我做错了什么吗?
只需使用下面的代码即可完成
def func(x):
res = x['cases']/x['population']
return res
df['prevalence'] = df.apply(func, axis=1)
输出
country year cases population prevalence
0 Afghanistan '99 745 19987071 0.000037
1 Brazil '99 37737 172006362 0.000219
2 China '99 212258 1272915272 0.000167
3 Afghanistan '00 2666 20595360 0.000129
4 Brazil '00 80488 174504898 0.000461
5 China '00 213766 1280428583 0.000167