繁体   English   中英

从Pandas DataFrame列中删除部分字符串

[英]Removing part of string from Pandas DataFrame column

我已将一组数据加载到如下所示的Pandas DataFrame中。

test['Consultation']
Out[13]: 
0     CONSULTATION      15.00
1     CONSULTATION      10.00
2     CONSULTATION      18.00
3     CONSULTATION       0.00
4     CONSULTATION      18.00

这些值包含在DataFrame“ Consultation”列中。

知道如何用空白替换“咨询”并将列数据类型转换为int64或float吗?

我的预期输出如下。

test['Consultation']
Out[13]: 
0     15.00
1     10.00
2     18.00
3      0.00
4     18.00

这是为了让我自己使用DataFrame.pivot_table('Consultation',rows='Provider')计算我的行字段的平均值。

为什么首先要以这种方式读取数据,难道不能只将其读入两列? 但是无论如何,可以做到这一点,注意:

In [35]:

df=pd.DataFrame({'Consultation':['CONSULTATION      15.00',
'CONSULTATION      10.00',
'CONSULTATION      18.00',
'CONSULTATION       0.00',
'CONSULTATION      18.00']})
In [36]:

import re
In [37]:

p=re.compile('[0-9.]+')
In [38]:

df['Cons']=df['Consultation'].apply(lambda x: float(p.findall(x)[0]))
In [39]:

print df
              Consultation  Cons
0  CONSULTATION      15.00    15
1  CONSULTATION      10.00    10
2  CONSULTATION      18.00    18
3  CONSULTATION       0.00     0
4  CONSULTATION      18.00    18

[5 rows x 2 columns]
In [40]:

df.dtypes
Out[40]:
Consultation     object
Cons            float64
dtype: object

您可以使用df['Consultation']=df['Consultation'].apply(lambda x: float(p.findall(x)[0]))覆盖原始df['Consultation'] df['Consultation']=df['Consultation'].apply(lambda x: float(p.findall(x)[0]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM