使用 Python 字典作为查找 table 输出新值
Use a Python dictionary as a lookup table to output new values
如果有更好的方法,我不喜欢使用字典进行查找table。我已经创建了一个简单的 Python 字典 (lkup) 用作查找 table 以及来自 df.letter 的输入。我想将字典中的映射值输出到新列 df.newletter。下面的代码片段一直运行到最后一行中的实际分配。
我试过只使用数字索引,使用键、值、dict.get() 和许多其他东西。我接近了吗?
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]
我想在 df.newletter 列中查看映射的字典值。
您不需要循环来执行此操作,只需将新列分配给使用 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
如果有更好的方法,我不喜欢使用字典进行查找table。我已经创建了一个简单的 Python 字典 (lkup) 用作查找 table 以及来自 df.letter 的输入。我想将字典中的映射值输出到新列 df.newletter。下面的代码片段一直运行到最后一行中的实际分配。
我试过只使用数字索引,使用键、值、dict.get() 和许多其他东西。我接近了吗?
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]
我想在 df.newletter 列中查看映射的字典值。
您不需要循环来执行此操作,只需将新列分配给使用 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