2017-07-12 46 views
1

我很新的python &熊猫,并有问题。 我有一系列需要编辑的45398个字符串。我从一个excel文件导入它们。字符串拆分在单个字符串上工作,但不是在熊猫系列的字符串

import pandas as pd 
import numpy as np 
import xlrd 

file_location = "#mypath/leistungen_2017.xlsx" 
workbook = xlrd.open_workbook(file_location) 
sheet = workbook.sheet_by_index(0)` 

df = pd.read_excel("leistungen_2017.xlsx") 

这是前面的几行,只是举例。

>>> df 
Leistungserbringer Anzahl Leistung Code Rechnungsnummer 
0 Albert 1 15.0160 Vollständige Spirometrie und Resistanc... 1 8957 
1 Albert 1 15.0200 CO-Diffusion, jede Methode 1 8957 
2 Albert 1 15.0285 Messung ausgeatmetes Stickstoffmonoxid... 1 8957 
3 Albert 1 AMC-30864 Spirometriefilter mit Mundstück 1 8957 
4 Albert 1 5889797 RELVAR ELLIPTA Inh Plv 92mcg/22mcg 30 Dos 1 8957 
5 Albert 1 00.0010 Konsultation, erste 5 Min. (Grundkonsu... 1 8957 

在第四列中,在文本前面有一串数字,我想在整个系列中删除它们。

我周围的测试单串并工作正常:

>>> str("15.0200 CO-Diffusion, jede Methode".split(' ', 1)[1:]).strip('[]')` 
"'CO-Diffusion, jede Methode'" 

我想这适用于整个系列:

for entry in df.Leistung: 
    df.Leistung.replace({entry : str(entry.split(' ', 1)[1:]).strip('[]')}, inplace=True) 

为df.Leistung结果看起来应该像这样:

0  Vollständige Spirometrie und Resistance (Plet... 
1        CO-Diffusion, jede Methode 
2   Messung ausgeatmetes Stickstoffmonoxid ({eNO}) 
3      Spirometriefilter mit Mundstück 
4    RELVAR ELLIPTA Inh Plv 92mcg/22mcg 30 Dos 
5   Konsultation, erste 5 Min. (Grundkonsultation) 

相反,我收到此:

0               
1               
2               
3               
4               
5 

一行给出了这样的:

45384 'Dos\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'"\\\\\\\\\... 

我需要更新旧系列在同一列的新系列。 我希望这是可以理解的,并提前感谢您发布任何帮助。

+0

谢谢@stephenmuss –

回答

1

你不需要循环熊猫,它都是矢量化的。您之后的替换函数属于.str.命名空间。所以你需要做的::

df.Leistung.str.replace(r'\d+', '') 
+0

谢谢你的提示,完美的作品! 还有一个“。”在每个句子的开头,但是不好的话也删除。我会赞成你的评论,但我的分数太低了。 –