在 Pandas 中将列转换为字符串 [英] Convert columns to string in Pandas

查看:72
本文介绍了在 Pandas 中将列转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下来自 SQL 查询的 DataFrame:

I have the following DataFrame from a SQL query:

(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 列转换为字符串而不是整数,以便我得到这个:

but I want to make sure the 303 columns are casted as strings instead of integers so that I get this:

{'3030096843': 1, '3030096845': 1, -1: 2}

推荐答案

转换为字符串的一种方法是使用 astype:

One way to convert to string is to use astype:

total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)

然而,也许您正在寻找to_json 函数,它会将键转换为有效的 json(因此将键转换为字符串):

However, perhaps you are looking for the to_json function, which will convert keys to valid json (and therefore your keys to strings):

In [11]: df = pd.DataFrame([['A', 2], ['A', 4], ['B', 6]])

In [12]: df.to_json()
Out[12]: '{"0":{"0":"A","1":"A","2":"B"},"1":{"0":2,"1":4,"2":6}}'

In [13]: df[0].to_json()
Out[13]: '{"0":"A","1":"A","2":"B"}'

注意:您可以传入一个缓冲区/文件来保存它,以及其他一些选项......

这篇关于在 Pandas 中将列转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆