还有另一种方法可以实现相同的功能。由于JSON由键(双引号中的字符串)和值(字符串,数字,嵌套的JSON或数组)组成,并且它非常类似于Python的字典,因此您可以使用简单的转换和字符串操作从Pandas DataFrame获取JSON。
import pandas as pd
df = pd.DataFrame([['τ', 'a', 1], ['π', 'b', 2]])
# convert index values to string (when they're something else - JSON requires strings for keys)
df.index = df.index.map(str)
# convert column names to string (when they're something else - JSON requires strings for keys)
df.columns = df.columns.map(str)
# convert DataFrame to dict, dict to string and simply jsonify quotes from single to double quotes
js = str(df.to_dict()).replace("'", '"')
print(js) # print or write to file or return as REST...anything you want
输出:
{"0": {"0": "τ", "1": "π"}, "1": {"0": "a", "1": "b"}, "2": {"0": 1, "1": 2}}
更新:
根据@Swier的提示(谢谢),原始数据框中包含双引号的字符串可能会出现问题。 df.jsonify() 会对它们进行转义(即'"a"'将在JSON格式中产生"\\"a\\"")。通过对字符串方法进行小的更新,也可以处理这个问题。完整示例:
import pandas as pd
def run_jsonifier(df):
# convert index values to string (when they're something else)
df.index = df.index.map(str)
# convert column names to string (when they're something else)
df.columns = df.columns.map(str)
# convert DataFrame to dict and dict to string
js = str(df.to_dict())
#store indices of double quote marks in string for later update
idx = [i for i, _ in enumerate(js) if _ == '"']
# jsonify quotes from single to double quotes
js = js.replace("'", '"')
# add \ to original double quotes to make it json-like escape sequence
for add, i in enumerate(idx):
js = js[:i+add] + '\\' + js[i+add:]
return js
# define double-quotes-rich dataframe
df = pd.DataFrame([['τ', '"a"', 1], ['π', 'this" breaks >>"<""< ', 2]])
# run our function to convert dataframe to json
print(run_jsonifier(df))
# run original `to_json()` to see difference
print(df.to_json())
输出:
{"0": {"0": "τ", "1": "π"}, "1": {"0": "\"a\"", "1": "this\" breaks >>\"<\"\"< "}, "2": {"0": 1, "1": 2}}
{"0":{"0":"\u03c4","1":"\u03c0"},"1":{"0":"\"a\"","1":"this\" breaks >>\"<\"\"< "},"2":{"0":1,"1":2}}
eval所需字段,然后再次转储JSON。 - Ayush Mandowara