我在审查一段Python代码(由于不常使用Python,所以不确定设计模式中的细微差别),看到以下的注释:
# Mutating dataframes in a loop isn't efficient and stylistic. TODO: find alternative
这段注释针对的是如下代码:
for id in ids:
rows4id = df.id == id
date2scale = get_date2scale(date4id[id])
df.loc[rows4id, "scale"] = df.loc[rows4id, "date"].map(date2scale)
如何重写这段代码以使其“更高效且风格更加优雅”?
示例数据:
import pandas as pd
df = pd.DataFrame({
"id": [0, 1, 2],
"date": [10, 10, 10],
"scale": [0, 0, 0]
})
ids = [1, 2]
def get_date2scale(id):
if id == 1:
return {10: 5.1}
elif id == 2:
return {10: 5.2}
else:
raise ValueError("Should not be called for this id")
期望的结果是:
df = pd.DataFrame({
"id": [0, 1, 2],
"date": [10, 10, 10],
"scale": [0, 5.1, 5.2]
})