import pandas as pd
d = {'a': [{"col1": 2, "col2": "hello", "col3": True},
{"col1": 2, "col2": "wrold", "col3": True}],
"b": [{"col1": 1, "col2": "helloword", "col3": True}]}
# pandas格式化输出,对dict类型数据进行操作
format_out: str = ""
for k, arr in d.items():
dic = arr[0]
merge_columns = list(dic.keys())
merge_columns.insert(0, k)
pp = pd.DataFrame.from_records(arr, columns=merge_columns)
for idx in range(len(arr)):
pp.iloc[idx,0] = int(idx+1)
pp[k]=pp[k].astype(int)
# 去掉index
out=pp.to_string(index=False)
# 将out转dataframe
df = pd.read_csv(io.StringIO(out), delim_whitespace=True)
# 再使用tabulate进行grid输出
grid_out=tabulate(df, headers='keys', tablefmt='grid', showindex=False)
format_out += grid_out
format_out +='\n'
print(format_out)
pass
pandas 输出dict
于 2023-12-14 20:36:44 首次发布