为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2021-06-05 04:42:27
我绝对是初学者。我在使用 Python 对 Excel 文件中的字符串进行切片时遇到问题。我的 Excel 文件包含以下信息:Column 1:ordercode   PMC11-AA1L1FAVWJA   PMC21-AA1A1CBVXJA   PMP11-AA1L1FAWJJ    PMP21-AA1A1FBWJJ    PMP23-AA1A1FA3EJ+JAPTP31B-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 filefile="Stratification_worksheet.xlsx"#Loading the spreadsheet data= pd.ExcelFile(file)#sheetnameprint(data.sheet_names)#loading the sheetname to df1df=data.parse("Auftrag")print(df)#creating a new column preessurerange and slicing the pressure range from order codefor 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)
查看完整描述

3 回答

  • 3 回答
  • 0 关注
  • 181 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号