有人可以帮助我在此数据框中创建两个新列吗?
期望将状态解析为“ s”,然后确保将状态从原始标题字符串中删除。结果将包括原始标题,清除的标题(不包含尾随的State)以及最后的状态名称。
df=pd.Series(['Accommodation Payroll Employment in Texas',
'Accounting, Tax Preparation, Bookkeeping, and Payroll Services Payroll Employment in Texas']).to_frame()
df.columns=['title']
def state_code(row):
t=None
s=None
if len(row['title'].split(' in '))==2:
s=str(row['title'].split(' in ')[1])
t=str(row['title'].split(' in ')[0])
elif len(row['title'].split(' in '))==3:
s=str(row['title'].split(' in ')[2])
t=str(row['title'].split(' in ')[0]+row['title'].split(' in ')[1])
elif len(row['title'].split(' for '))==2:
s=str(row['title'].split(' for ')[1])
t=str(row['title'].split(' for ')[0])
return t,s
df[['title_clean','state']]=df.apply(state_code,axis=1)
最佳答案
代替
return t, s
尝试
return pd.Series(dict(state=s, title_clean=t))
而不是
df[['title_clean','state']]=df.apply(state_code,axis=1)
采用
pd.concat([df, df.apply(state_code,axis=1)], axis=1)
顺便说一句
t = None
s = None
似乎多余。