使用 pandas 将字符串前缀添加到字符串列中的每个值 [英] add a string prefix to each value in a string column using Pandas
本文介绍了使用 pandas 将字符串前缀添加到字符串列中的每个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个字符串附加到pandas数据框的所述列中每个值的开头. 我已经弄清楚该如何做,目前正在使用:
I would like to append a string to the start of each value in a said column of a pandas dataframe (elegantly). I already figured out how to kind-of do this and I am currently using:
df.ix[(df['col'] != False), 'col'] = 'str'+df[(df['col'] != False), 'col']
这似乎是一件微不足道的事情-您是否知道其他任何方式(可能还会将该字符添加到该列为0或NaN的行中)?
This seems one hell of an inelegant thing to do - do you know any other way (which maybe also adds the character to rows where that column is 0 or NaN)?
如果尚不清楚,我想转一下:
In case this is yet unclear, I would like to turn:
col
1 a
2 0
进入:
col
1 stra
2 str0
推荐答案
df['col'] = 'str' + df['col'].astype(str)
示例:
>>> df = pd.DataFrame({'col':['a',0]})
>>> df
col
0 a
1 0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
col
0 stra
1 str0
这篇关于使用 pandas 将字符串前缀添加到字符串列中的每个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文