【问题标题】:string split on single strings works, but not on series of strings in pandas单个字符串上的字符串拆分有效,但不适用于 pandas 中的一系列字符串
【发布时间】:2017-12-16 20:33:54
【问题描述】:

我对 python 和 pandas 很陌生,但遇到了一个问题。 我有一系列需要编辑的 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\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'"\\\\\\\\\...

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

【问题讨论】:

    标签: python excel string pandas split


    【解决方案1】:

    你不需要 pandas 中的循环,它都是矢量化的。您所追求的替换功能属于 .str. 命名空间。所以你需要做::

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

    【讨论】:

    • 感谢您的提示,完美运行!还有一个“。”在每个句子的开头,但也将其删除。我会赞成你的评论,但我的分数太低了。
    猜你喜欢
    • 2011-12-30
    • 2015-08-29
    • 1970-01-01
    • 2023-03-08
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多