使用Python从列的每一行中的字符串中切片子字符串

我绝对是初学者。我在使用 Python 对 Excel 文件中的字符串进行切片时遇到问题。我的 Excel 文件包含以下信息:


Column 1:


ordercode   

PMC11-AA1L1FAVWJA   

PMC21-AA1A1CBVXJA   

PMP11-AA1L1FAWJJ    

PMP21-AA1A1FBWJJ    

PMP23-AA1A1FA3EJ+JA

PTP31B-AA3D1HGBVXJ  

PTC31B-AA3D1CGBWBJA 

PTP33B-AA3D1HGB1JJ  

我想根据

“PMC11”/“PMC21”/“PMP21”/“PMP11”/“PMP23”/“PTP31B”/“PTP33B”/“PTC31B”在不同位置对列“ordercode”中的字符串进行切片并将其保存在新列“压力范围”中。在 Excel 中,我使用了以下代码并且运行良好:


=IF(OR(ISNUMBER(SEARCH("PMC11",A2)),ISNUMBER(SEARCH("PMC21",A2)),ISNUMBER(SEARCH("PMP11",A2)),ISNUMBER(SEARCH("PMP21",A2)),ISNUMBER(SEARCH("PMP23",A2))),MID(A2,11,2),MID(A2,12,2))

但是在 Python 中我使用了下面的编码,但它不能正常工作。


蟒蛇代码:


import pandas as pd

#Assigning the worksheet to file

file="Stratification_worksheet.xlsx"

#Loading the spreadsheet 

data= pd.ExcelFile(file)

#sheetname

print(data.sheet_names)

#loading the sheetname to df1

df=data.parse("Auftrag")

print(df)


#creating a new column preessurerange and slicing the pressure range from order code


for index,row in df.iterrows():

    if "PMC11" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(10,12)

    elif "PMC21" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(10,12)

    elif "PMP11" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(10,12)

    elif "PMP21" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(10,12)

    elif "PMP23" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(10,12)

    elif "PTP31B" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(11,13)

    elif "PTP33B" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(11,13)

    elif "PTC31B" in df.loc[index,"ordercode"]:

        df["pressurerange"]=df["ordercode"].str.slice(11,13)


这里它所做的是检查第一个 IF 条件,并在所有列的位置 (10,12) 处对字符串进行切片。我知道我在下面的代码中犯了错误。但我不知道要使用的确切代码是什么。


=df["pressurerange"]=df["ordercode"].str.slice(10,12)


绝地无双
浏览 182回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python