【发布时间】:2020-01-28 15:43:27
【问题描述】:
我有一个包含产品代码和产品类型的数据框。
material_description component_type_or_status
SF 1243545gbe ff ee rr oo SF
LF 2324344ire ff ee rr oo LF
BF 3434333fre ff gg hh 23 BF
IA SF 3434333fre ff gg 22 re IA
ZZ LF 34391r33b ff tn 33 ZZ
我想创建一个名为材料代码的新列,它根据产品类型的值从产品代码列左侧提取第二个字符串或第三个字符串
如果 SF、BF 或 LF 在左侧第一个空格之后返回字符串
如果 IA 或 ZZ 在左数第二个空格后返回字符串
这是我的功能。它陷入了一个循环,我不确定我的逻辑是否正确。 使用 Pandas 执行此操作的最佳方法是什么?
def parse_material_description(x):
df = infile.parse(sheet_name='Unit of Measure')
df['component_type_or_status'] = df['Material Description'].str[:2]
try:
if x['component_type_or_status'] == 'SF':
df['material_code'] = df['Material Description'].str.split(" ",1)
elif x['component_type_or_status'] == 'LF':
df['material_code'] = df['Material Description'].str.split(" ",1)
elif x['component_type_or_status'] == 'BF':
df['material_code'] = df['Material Description'].str.split(" ",1)
elif x['component_type_or_status'] == 'IA':
df['material_code'] = df['Material Description'].str.split(" ",2)
elif x['component_type_or_status'] == 'ZZ':
df['material_code'] = df['Material Description'].str.split(" ",2)
elif x['component_type_or_status'] == None:
return ''
except: IndexError
df['component_type_or_status'] = df.apply(parse_material_description, axis=1)
【问题讨论】: