[英]How to remove % symbol for particular column in dataframeusing python pandas?
My data frame have following data: 我的数据框包含以下数据:
company,standard,returns
aaa,b1,10%
bbb,b2,20%
I have to remove %
from returns
column. 我必须从
returns
栏中删除%
。
First remove last value of each string by indexing with str and then cast to int
or float
: 首先使用str索引删除每个字符串的最后一个值,然后将其
int
为int
或float
:
#if int values
print (df['returns'].str[:-1].astype(int))
#if flaot values
print (df['returns'].str[:-1].astype(float))
Sample: 样品:
print (df)
company standard returns
0 tata b1 10%
1 dell b2 10%
#if int values
df['returns'] = (df['returns'].str[:-1].astype(int))
print (df)
company standard returns
0 tata b1 10
1 dell b2 10
Another solution with str.strip
: str.strip
另一个解决方案:
df['returns'] = (df['returns'].str.strip('%').astype(int))
print (df)
company standard returns
0 tata b1 10
1 dell b2 10
Use vectorized str.replace
: 使用向量化的
str.replace
:
In [225]:
df['returns'] = df['returns'].str.replace('\%','')
df
Out[225]:
company standard returns
0 aaa b1 10
1 bbb b2 20
You can cast the dtype
afterwards using astype(int)
or astype(float)
你可以投的
dtype
之后使用astype(int)
或astype(float)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.