我正在尝试使用行中的其他值为较低的置信区间创建一个新列。我已将置信区间计算编写为(并发布)为 pypi
上的 public-health-cis
包。这些函数接受浮点值并返回浮点值。
在我的分析脚本中,我尝试从 pandas 数据帧调用此函数。我尝试了多种选择来尝试使其正常工作,但均无济于事。
df_for_ci_calcs = df[['Value', 'Count', 'Denominator']].copy()
df_for_ci_calcs = df_for_ci_calcs.applymap(lambda x: -1 if x == '*' else x)
df_for_ci_calcs = df_for_ci_calcs.astype(np.float)
df['LowerCI'].apply(lambda x: public_health_cis.wilson_lower(df_for_ci_calcs['Value'].astype(float),
df_for_ci_calcs['Count'].astype(float),
df_for_ci_calcs['Denominator'].astype(float), indicator.rate))
返回此回溯:
Internal Server Error: /
df['LowerCI'].apply(lambda x: public_health_cis.wilson_lower(df_for_ci_calcs['Value'].astype(float), df_for_ci_calcs['Count'].astype(float), df_for_ci_calcs['Denominator'].astype(float), indica
tor.rate))
TypeError: cannot convert the series to <class 'float'>
我也尝试过使用:
df['LowerCI'] = df_for_ci_calcs.applymap(lambda x: public_health_cis.wilson_lower(df_for_ci_calcs['Value'], df_for_ci_calcs['Count'],
df_for_ci_calcs['Denominator'], indicator.rate), axis=1)
这会产生错误:
applymap() 收到意外的关键字参数“axis”
当我取出轴 kwarg 时,我得到与第一种方法相同的错误。那么,如何将每行中的值传递到函数中以根据这些行中的数据获取值?
最佳答案
我认为你需要apply
使用 axis=1
按行进行处理,因此将输入作为 float
s:
df['LowerCI'] = df[['Value', 'Count', 'Denominator']]
.replace('*', -1)
.astype(float)
.apply(lambda x: public_health_cis.wilson_lower(x['Value'],
x['Count'],
x['Denominator'],
indicator.rate),
axis=1)
示例(为了简化,我将 indicator.rate
更改为标量 100
):
df = pd.DataFrame({'Value':['*',2,3],
'Count':[4,5,6],
'Denominator':[7,8,'*'],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (df)
Count D Denominator E F Value
0 4 1 7 5 7 *
1 5 3 8 3 4 2
2 6 5 * 6 3 3
df['LowerCI'] = df[['Value', 'Count', 'Denominator']] \
.replace('*', -1) \
.astype(float) \
.apply(lambda x: public_health_cis.wilson_lower(x['Value'],
x['Count'],
x['Denominator'],
100), axis=1)
print (df)
Count D Denominator E F Value LowerCI
0 4 1 7 5 7 * 14.185885
1 5 3 8 3 4 2 18.376210
2 6 5 * 6 3 3 99.144602
关于python - 将列值传递到 Pandas 中的 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282210/