【发布时间】:2020-01-01 09:31:06
【问题描述】:
我想从两列中提取一个项目,使用 np.where,DataFrame 如下: (总共 100,000+ 行)
添加说明:“eNBID”并不总是“ID”的第三部分,数据非常脏。
ID eNBID
460-00-2354-9 2354
4600023549 2354
46001368511 6789
4600332783112 32783
我想要的结果是:
ID eNBID CI
460-00-2354-9 2354 9
4600023549 2354 9
46001368511 6789 11
4600332783112 32783 112
我的代码是:
df['Ci'] = np.where(df['ID'].astype(str).str.contains(r'-',na=False,regex=True), \
df['ID'].apply(lambda x:re.split('-',str(x))[-1], \
df.apply(lambda x:re.findall('([\w]{5})'+'([\w]{%d}'%(len(str(x.eNBID)))+'(\w*)',str(x.ID))[0][-1], axis=1))
错误是:
IndexError:('list index out of range','occurred at index 0')
这是我的新代码:
cond = df['ID'].astype(str).str.contains('-',na=False,regex=True)
df['CI'] = np.where(cond,df['ID'].apply(lambda x:re.split('-',str(x))[-1]), \
df[~cond].apply(lambda x:re.findall('([\w]{5})'+'([\w]{%d}'%(len(str(x.eNBID)))+'(\w*)',str(x.ID))[0][-1], axis=1)) if len(str(x.eNBID))<(len(str(x.ID))-5) else "null", axis=1))
错误是:
ValueError:operands could not be broadcast together with shapes(100883,)(100883,)(78,)
谁能帮帮我?
【问题讨论】:
-
@Erfan 我假设 CI 是在 eNBID 之后的 ID 中找到的数字(至少这与提供的示例一致)
-
对不起,是我的错,我没说清楚,“eNBID”并不总是“ID”的第三部分,数据很脏,只有“eNBID”的长度"可以使用。
标签: pandas numpy data-cleaning