将pandas dataframe中的列从int转换为string [英] Converting a column within pandas dataframe from int to string

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

问题描述

我刚刚开始使用大熊猫。
我在pandas中有一个带有混合int和str数据列的数据帧。我想连接数据框中的第一列,为此我必须将 int 列转换为 str
我试过这样做:

I'm just starting to work with pandas. I have a dataframe in pandas with mixed int and str data columns. I want to concatenate first columns within the dataframe, to do that I have to convert int column to str. I've tried to do that like that:

mtrx['X.3'] = mtrx.to_string(columns = ['X.3'])

或类似

mtrx['X.3'] = mtrx['X.3'].astype(str)

但在这两种情况下它都无法正常工作,我收到的错误是无法连接'str'和'int'对象。两个 str 列的Concat工作正常。

but in both cases it's not working and I'm getting an error saying "cannot concatenate 'str' and 'int' objects". Concat for two str columns is working perfectly fine.

任何帮助都将不胜感激!谢谢!

Any help would be greatly appreciated! Thanks!

推荐答案

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

转换系列

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

转换整个框架

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

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

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