python-3.x - Use a Python dictionary as a lookup table to output new values
问题描述
I'm not attached to using a dictionary for a lookup table, if there's a better way to go. I've created a simple Python dictionary (lkup) to use as a lookup table with input from df.letter. I'd like to output the mapped values from the dictionary into a new column, df.newletter. The snippet below works up until the actual assignment in the final line.
I've tried using only numeric indexes, using keys, values, dict.get(), and a number of other things. Am I close?
import pandas as pd
df = pd.DataFrame()
df['letter'] = ['a', 'a', 'c', 'd', 'd']
lkup = {'a':'b', 'b':'c', 'c':'d', 'd':'e', 'e':'f'}
for key in lkup:
for i in range(0,4):
if df['letter'][i] in key:
df['newletter'][i] = [insert_dictionary_value]
I'd like to see the mapped dictionary values in the df.newletter column.
解决方案
You don't need a loop to do that, just assign the new column to values of the old column mapped by the dictionary using df.map
:
...
>>> df['newletter'] = df['letter'].map(lkup)
>>> print(df)
letter newletter
0 a b
1 a b
2 c d
3 d e
4 d e
推荐阅读
- c++ - GNU MPFR 在精度高于 64 时给我完全相同的结果
- performance - 是否有任何已建立的带有时间分析的 spark-sql 表达式的性能基准?
- mysql - 如何在客户端列中每个唯一值的描述中创建获取 3 个值
- firebase - Firebase Firestore - 在 React Native 中显示查询的数据
- algorithm - 有没有比欧拉五边形数定理更好的算法来计算分区数 p(n)
- c++ - C++ 错误 C2665:2 个重载都不能转换所有 arg 类型
- winapi - MediaFoundation 在预览时捕捉视频
- javascript - 如何将 v-model 设置为 v-for 循环中子属性的子值?
- flutter - 检查是否已将 Flutter Web 应用程序 (PWA) 添加到主屏幕?
- groovy - 输入消息不适用于提交者值