我有一個包含多個產品名稱的列,例如 Contract0 O.U201 O.Z202 O.H213 O.M214 O.U215 O.Z216 O.H227 O.M228 S3.U209 S3.Z2010 S6.M2611 S6.U2612 S6.Z2613 S6.H2714 S9.U2615 S9.Z2616 F3.U2617 F3.Z2618 F3.H2719 F6.H2620 F6.M2621 F6.U2622 F9.U20我想要做的是根據合同名稱分配部分名稱,例如 Contract Sections0 O.U20 O11 O.Z20 O12 O.H21 O13 O.M21 O14 O.U21 O25 O.Z21 O26 O.H22 O27 O.M22 O28 S3.U20 S39 S3.Z20 S310 S6.M26 S611 S6.U26 S612 S6.Z26 S613 S6.H27 S614 S9.U26 S915 S9.Z26 S916 F3.U26 F317 F3.Z26 F318 F3.H27 F319 F6.H26 F620 F6.M26 F621 F6.U26 F622 F9.U20 F9對于 S 和 F 系列,我可以使用此代碼實現所需的結果(如果有更好的實現方法,請告訴我)df.loc[df['Contract'].str.contains('S3'),'Sections'] = 'S3'df.loc[df['Contract'].str.contains('S6'),'Sections'] = 'S6'df.loc[df['Contract'].str.contains('S9'),'Sections'] = 'S9'df.loc[df['Contract'].str.contains('F3'),'Sections'] = 'F3'df.loc[df['Contract'].str.contains('F6'),'Sections'] = 'F6'df.loc[df['Contract'].str.contains('F9'),'Sections'] = 'F9'因為它只是匹配分配部分名稱的字符串。遺憾的是 O 系列沒有附加數字,所以我必須將它分成 4 個塊,如上所示 Contract Sections0 O.U20 O11 O.Z20 O12 O.H21 O13 O.M21 O14 O.U21 O25 O.Z21 O26 O.H22 O27 O.M22 O2我嘗試了以下代碼df.loc[df['Contract'].str.contains('O'),'Sections'] = df.index // 4+1但它拋出錯誤ValueError: could not broadcast input array from shape (23) into shape (8)我怎樣才能以更好、更有效的方式取得成果?請注意,這只是一個樣本數據,原始數據集有更多這樣的值。
2 回答

www說
TA貢獻1775條經驗 獲得超8個贊
將您的代碼更改為
df.loc[df['Contract'].str.contains('O'),'Sections'] = 'O' +((df['Contract'].str.contains('O').cumsum().sub(1)//4) + 1).astype(str)

函數式編程
TA貢獻1807條經驗 獲得超9個贊
為了簡化
df.loc[df['Contract'].str.contains('S3'),'Sections'] = 'S3'
df.loc[df['Contract'].str.contains('S6'),'Sections'] = 'S6'
df.loc[df['Contract'].str.contains('S9'),'Sections'] = 'S9'
df.loc[df['Contract'].str.contains('F3'),'Sections'] = 'F3'
df.loc[df['Contract'].str.contains('F6'),'Sections'] = 'F6'
df.loc[df['Contract'].str.contains('F9'),'Sections'] = 'F9'
只需將其替換為以下 1 行代碼:
df['Section'] = df['Contract'].str.split('.').str[0]
添加回答
舉報
0/150
提交
取消