dataframe 怎么转str,将pandas dataframe中的列从int转换为string

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'])

or like that

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

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

Convert a series

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'

Convert the whole frame

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'

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值