python - 熊猫适用,“浮动”对象不可下标
问题描述
我有以下数据框:
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
你知道为什么吗 ?
解决方案
将numpy.where
withSeries.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
推荐阅读
- javascript - 从弹出窗口设置 localStorage
- android-broadcast - 如何在 Android Oreo 中接收 PROVIDERS_CHANGED 广播
- arrays - 在Vue / Vuex中将数据插入动态数组
- java - 如何在java中访问地图的特定值?
- python - Python 正则表达式:在引号之间跳过分隔符的问题
- angular - 将 Angular 2 升级到 Angular 6
- php - 使用 PHP 将 LONGBLOB 文件从一个表复制到另一个表
- android - 如何在片段 java 文件中添加功能以共享我在主页片段中创建的按钮?
- javascript - Reactjs-router-dom 和 cordova 总是直接指向 file:///android_asset/www/index.html
- node.js - 从 Node 调用 Angular 会产生错误