温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Pandas apply, 'float' object is not subscriptable
apply pandas python syntax

python - pandas 适用,“浮动”对象不可下标

发布于 2020-03-29 21:56:32

我有以下数据框:

Y = list(range(5))
Z = np.full(5, np.nan)
df = pd.DataFrame(dict(ColY = Y, ColZ = Z))
print(df)
   ColY  ColZ
0     0   NaN
1     1   NaN
2     2   NaN
3     3   NaN
4     4   NaN

这本字典:

Dict = {
    0 : 1,
    1 : 2,
    2 : 3,
    3 : 2,
    4 : 1
}

如果通过Dict的ColY的对应值是2,我想用“ ok”填充ColZ。因此,我想要以下数据框:

   ColY ColZ
0     0  NaN
1     1   ok
2     2  NaN
3     3   ok
4     4  NaN

我尝试了以下脚本:

df['ColZ'] = df['ColZ'].apply(lambda x : "ok" if Dict[x['ColY']] == 2 else Dict[x['ColY']])

我有这个错误:

TypeError: 'float' object is not subscriptable

你知道为什么吗 ?

查看更多

提问者
Ewdlam
被浏览
105
jezrael 2020-01-31 21:54

用于numpy.whereSeries.map新系列进行比较Series.eq==):

df['ColZ'] = np.where(df['ColY'].map(Dict).eq(2), 'ok', np.nan)
print(df)
   ColY ColZ
0     0  nan
1     1   ok
2     2  nan
3     3   ok
4     4  nan

详细说明

print(df['ColY'].map(Dict))
0    1
1    2
2    3
3    2
4    1
Name: ColY, dtype: int64

您的解决方案应更改.get为返回一些默认值,np.nan如果不匹配,请在此处输入

df['ColZ'] = df['ColY'].apply(lambda x : "ok" if Dict.get(x, np.nan) == 2 else np.nan)

编辑:对于使用df['ColZ']值的集,请使用:

Y = list(range(5))
Z = list('abcde')
df = pd.DataFrame(dict(ColY = Y, ColZ = Z))
print(df)
Dict = {
    0 : 1,
    1 : 2,
    2 : 3,
    3 : 2,
    4 : 1
}

df['ColZ1'] = np.where(df['ColY'].map(Dict).eq(2), 'ok', df['ColZ'])
df['ColZ2'] = df.apply(lambda x : "ok" if Dict.get(x['ColY'], np.nan) == 2 
                                       else x['ColZ'], axis=1)
print (df)
   ColY ColZ ColZ1 ColZ2
0     0    a     a     a
1     1    b    ok    ok
2     2    c     c     c
3     3    d    ok    ok
4     4    e     e     e