使用 Pandas 为字符串列中的每个值添加字符串前缀 [英] add a string prefix to each value in a string column using Pandas
本文介绍了使用 Pandas 为字符串列中的每个值添加字符串前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Pandas 数据帧的所述列中的每个值的开头附加一个字符串(优雅地).我已经想出了如何做到这一点,我目前正在使用:
df.ix[(df['col'] != False), 'col'] = 'str'+df[(df['col'] != False), 'col']
这似乎是一件非常不雅的事情 - 您知道其他任何方式吗(这可能还会将字符添加到该列为 0 或 NaN 的行中)?
如果还不清楚,我想转:
列1个2 0
进入:
列1 条2 字符串
解决方案
df['col'] = 'str' + df['col'].astype(str)
示例:
<预><代码>>>>df = pd.DataFrame({'col':['a',0]})>>>df上校0个1 0>>>df['col'] = 'str' + df['col'].astype(str)>>>df上校0 条1 字符串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']
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
into:
col
1 stra
2 str0
解决方案
df['col'] = 'str' + df['col'].astype(str)
Example:
>>> 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屋!
查看全文