Pandas DataFrame to_json() 生成带点符号的索引

Pandas DataFrame to_json() results in index with dot notation

我有一个 Pandas DataFrame,我需要将其转换为 JSON。 to_json() DataFrame 方法生成可接受的格式,但它将我的 DataFrame 索引转换为字符串(例如 0 变为“0.0”)。我需要“0”。

DataFrame来自JSON,使用pd.io.json.read_json()方法,将索引设置为float64。

输入JSON:

{"chemical": {"1": "chem2", "0": "chem1"}, 
"type": {"1": "pesticide", "0": "pesticide"}}

DataFrame(来自read_json()):

  chemical  type
0 chem1    pesticide
1 chem2    pesticide

制作JSON(来自to_json()):

{"chemical": {"0.0": "chem1", "1.0": "chem2"},
"type": {"0.0": "pesticide", "1.0": "pesticide"}}

需要JSON:

{"chemical": {"0": "chem1", "1": "chem2"},
"type": {"0": "pesticide", "1": "pesticide"}}

索引的 dtype 似乎是 float(检查 df.index.dtype)。您需要将其转换为 int:

df.index = df.index.astype(int)
df.to_json()
=> {"chemical": {"0": "chem1", "1": "chem2"}, "type": {"0": "pesticide", "1": "pesticide"}}

@shx2 为我指出了正确的方向,但我改变了从 JSON 创建 DataFrame 的方法。

我没有在 JSON 字符串上使用 to_json() 方法,而是在 JSON 上使用 pd.DataFrame.from_dict() 方法作为 Python 字典来创建数据框。这导致 df.index.dtype == dtype('O')

我必须在 from_dict() 方法中设置 dtype='float64' 来为非字符串条目设置正确的数据类型。

pd_obj = pd.DataFrame.from_dict(request.json["inputs"], dtype='float64')