我有来自 SQL 查询的以下 DataFrame:
(Pdb) pp total_rows
ColumnID RespondentCount
0 -1 2
1 3030096843 1
2 3030096845 1
我想像这样旋转它:
total_data = total_rows.pivot_table(cols=['ColumnID'])
(Pdb) pp total_data
ColumnID -1 3030096843 3030096845
RespondentCount 2 1 1
[1 rows x 3 columns]
total_rows.pivot_table(cols=['ColumnID']).to_dict('records')[0]
{3030096843: 1, 3030096845: 1, -1: 2}
但我想确保将 303 列转换为字符串而不是整数,以便我得到这个:
{'3030096843': 1, '3030096845': 1, -1: 2}
原文由 sontek 发布,翻译遵循 CC BY-SA 4.0 许可协议
转换为字符串的一种方法是使用 astype :
但是,也许您正在寻找
to_json
函数,它将键转换为有效的 json(因此您的键转换为字符串):注意:您可以传入缓冲区/文件以将其保存到,以及其他一些选项…