我正在嘗試撰寫一個腳本,該腳本采用字典中的鍵并將它們替換為它們映射到 CSV 檔案中的值。我在嘗試查找匹配行時遇到問題。
CSV 檔案
QuestionKey,QuestionId
BASIC1,F4AB5C41-5BB2-41BD-AF7C-08E76BA05DCE
BASIC2,1E6D5B13-BDD2-43E7-9B74-36AD8C816A9C
腳本:
QUESTIONS_MAP = pd.read_csv('data/question_ids.csv', dtype=str)
def replace_questions_ids_with_keys(content: dict) -> dict:
"""Replace the question ids with the keys used in the decision response"""
# LOGGER.info(QUESTIONS_MAP)
for key, value in content.items():
# LOGGER.info(QUESTIONS_MAP.QuestionId)
# Find item QuestionKey for item in QUESTIONS_MAP where key in QuestionId
question_key = list(filter(lambda x: key in x['QuestionId'], QUESTIONS_MAP))
LOGGER.info(question_key)
if question_key:
content[QUESTIONS_MAP[key]] = value
del content[key]
return content
示例content字典:
{'F4AB5C41-5BB2-41BD-AF7C-08E76BA05DCE': '', '1E6D5B13-BDD2-43E7-9B74-36AD8C816A9C': ''}
運行時錯誤:
2022-05-18 14:46:55,340 - ERROR - string indices must be integers
預期回應:
{'BASIC1': '', 'BASIC2': ''}
uj5u.com熱心網友回復:
首先,使用 dict 比使用資料框更方便。因此,
# map question id -> question key
# squeeze tells pandas to produce a series when there's only one column
# index=1 tells it to use question id as an index
# finally, .to_dict() makes a dictionary out of the series
QUESTIONS_MAP = pd.read_csv('filename.csv', squeeze=True, index_col=1).to_dict()
然后,只需使用 dict 理解:
content = {
QUESTIONS_MAP[id_]: value
for id_, value in content.items()
if id_ in QUESTIONS_MAP
}
uj5u.com熱心網友回復:
恕我直言,我認為使用資料框(和熊貓)對于我所看到的來說太過分了。
這是一個簡單的解決方案:
import pandas as pd
QUESTIONS_MAP = pd.read_csv('data/question_ids.csv', dtype=str)
def replace_questions_ids_with_keys(content: dict) -> dict:
"""Replace the question ids with the keys used in the decision response"""
result = {}
for key, value in content.items():
for i in range(len(QUESTIONS_MAP)):
question_key = QUESTIONS_MAP.values[i][0]
question_id = QUESTIONS_MAP.values[i][1]
if question_id == key:
result[question_key] = ""
return result
my_dict = {'F4AB5C41-5BB2-41BD-AF7C-08E76BA05DCE': '', '1E6D5B13-BDD2-43E7-9B74-36AD8C816A9C': ''}
replace_questions_ids_with_keys(my_dict)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477166.html
