在Pandas中将列转换为字符串

8 浏览
0 Comments

在Pandas中将列转换为字符串

我从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]

当我将这个DataFrame转换为字典(使用total_data.to_dict(\'records\')[0])时,我得到的结果是:

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

但我想确保将303列转换为字符串而不是整数,以便获得以下结果:

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

admin 更改状态以发布 2023年5月22日
0
0 Comments

如果要将所有的列都转换成字符串,可以直接使用以下方法:\n

df = df.astype(str)

\n如果您只需要其中几列是字符串/对象类型的,可以先将所有列都转换成字符串/对象,然后再将其他需要的列转换为相应的类型(如整数):\n

 df[["D", "E"]] = df[["D", "E"]].astype(int) 

0
0 Comments

将数据转换成字符串的方式之一是使用 astype:

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

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

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"}'

注意: 你可以传入一个缓冲区/文件来保存这个数据,并包括一些其他选项...

0