Pandas 使用熊猫&x27;s应用于计算值-键错误
我有一个熊猫数据框,看起来像这样:Pandas 使用熊猫&x27;s应用于计算值-键错误,pandas,pandas-apply,Pandas,Pandas Apply,我有一个熊猫数据框,看起来像这样: 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
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
我想添加一个名为“流行率”的新列,它是按人口划分的世界卫生组织病例数。这一行代码起作用:
G['prevalence'] = G['cases'] / G['population']
然而,我想用Panda的apply做同样的事情。以下是我想做的:
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)
我得到一个关键错误:“流行率”
你知道我做错了什么吗?只需使用下面的代码即可
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