解决方案
df = pd.DataFrame({'Col1': ['ABS', 'CDC', 'POP'],
'Col2': [45, 23, 15],
})
keys = aa.keys()
df.Col1 = [''.join([aa.get(e) if (e in keys) else e for e in list(ee)]) for ee in df.Col1.tolist()]
df
输出:
解压精简列表理解
让我们以更易读的形式写下列表推导式。我们创建了一个函数do_something 来了解列表理解的第一部分发生了什么。第二部分 (for ee in df.Col1.tolist()) 本质上是遍历数据框 df 的列 'Col1' 中的每一行。
def do_something(x):
# here x is like 'ABS'
xx = '.join([aa.get(e) if (e in keys) else e for e in list(x)])
return xx
df.Col1 = [do_something(ee) for ee in df.Col1.tolist()]
开箱do_something(x)
函数do_something(x) 执行以下操作。如果您尝试使用x = 'ABS' 会更容易。 do_something 中的 ''.join(some_list) 加入了生成的列表。下面的代码块将说明这一点。
x = 'ABS'
print(do_something(x))
[aa.get(e) if (e in keys) else e for e in list(x)]
输出:
ADBS
['AD', 'B', 'S']
那么核心逻辑是什么?
以下代码块逐步向您展示了该逻辑的工作原理。显然,解决方案开头引入的list comprehension 将nested for loops 压缩为一行,因此应该优先于以下内容。
keys = aa.keys()
packlist = list()
for ee in df.Col1.tolist():
# Here we iterate over each element of
# the dataframe's column (df.Col1)
# make a temporary list
templist = list()
for e in list(ee):
# here e is a single character of the string ee
# example: list('ABS') = ['A', 'B', 'S']
if e in keys:
# if e is one of the keys in the dict aa
# append the corresponding value to templist
templist.append(aa.get(e))
else:
# if e is not a key in the dict aa
# append e itself to templist
templist.append(e)
# append a copy of templist to packlist
packlist.append(templist.copy())
# Finally assign the list: packlist to df.Col1
# to update the column values
df.Col1 = packlist
参考文献
列表和字典推导是任何 Python 程序员在编码时都会发现的一些非常强大的工具。他们有能力将原本复杂的代码块巧妙地压缩成一两行。我建议你看看以下内容。
- List Comprehensions:
python.org
- Dict Comprehensions:
python.org
- List Comprehension in Python:
medium.com