【问题标题】:How to save user inputs to a config/json file for later use?如何将用户输入保存到 config/json 文件以供以后使用?
【发布时间】:2018-08-30 18:09:50
【问题描述】:

我有一个函数从用户那里获取数据集中每个错误列名的用户输入。

例如,如果主数据集的列名称为 X、Y、Z,但子数据集的列名称为 A、B、C。我让用户输入正确的名称以将其与主数据集匹配。我将每个错误的名称保存为键,将正确的名称保存为字典中的值,如下所示:

    {"A":"X", "B":"Y", "C":"Z"}

我将该字典保存为 json 文件。我不希望用户在稍后再次运行代码时输入他们之前输入的相同名称,并且它应该从我们之前创建的字典中引用。

我可以在第一次运行时创建字典,但我不知道如何在下次运行时检查字典以及如何首先从字典中获取参考。

【问题讨论】:

标签: python json python-3.x pandas dictionary


【解决方案1】:

这是一个完整的例子。第一部分是将您的字典写入 JSON 文件。第二部分是当您想要加载该 JSON 文件并稍后重命名您的列时。

import json
import pandas as pd

json_file = "/Users/jkornblum/Desktop/cols.json"
df = pd.DataFrame(columns=["A", "B", "C"])

# You would return col_map from your function that accepts user input
col_map = {"A":"X", "B":"Y", "C":"Z"}

# Write column map to disk
with open(json_file, 'w') as outfile:
    json.dump(col_map, outfile)

# Read the column map and apply
col_map = None # Clear col_map for example
with open(json_file, 'r') as infile:
    col_map = json.load(infile)

# rename the dataframe columns
df = df.rename(columns=col_map)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2020-09-15
    • 2017-02-23
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多