【发布时间】:2019-10-31 14:21:12
【问题描述】:
我想用“ - ”分割数据框特定列的字符串,并将最后一部分保存到新列中。这在 df 之外有效:
s0 = '34 years old woman with pain in her XXX - Pharyngitis'
s1 = '67 years old man with xxx - yyy zzz - Nephropathy'
s2 = 'Metastatic Liver Cancer'
print(s0.split(" - ")[-1]) # works
print(s1.split(" - ")[-1])
print(s2.split(" - ")[-1])
但不是数据框:
df = pd.DataFrame([s0, s1, s2], columns=['title'])
df['diagnosis'] = df['title'].str.split(' - ')[-1] # KeyError: -1
print(df['diagnosis'])
我做错了什么?
【问题讨论】:
-
我不确定负索引是否适用于数据框。 df.str.split() 返回一个数据框,因此您必须将第一个数据框与新的数据框合并。