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

查看:3890
本文介绍了在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}

推荐答案

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

One way to convert to string is to use astype:

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

但是,也许您正在寻找 函数,该函数会将密钥转换为有效的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天全站免登陆