【问题标题】:Splitting a Python data frame string and saving the last split part into new column拆分 Python 数据框字符串并将最后一个拆分部分保存到新列中
【发布时间】: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() 返回一个数据框,因此您必须将第一个数据框与新的数据框合并。

标签: python dataframe split


【解决方案1】:

而不是将字符串拆分为块列表 - pd.Series.str.rfind 是一种方法:

In [104]: df['title'].apply(lambda s: s[s.rfind('-') + 1:].strip())                                         
Out[104]: 
0                Pharyngitis
1                Nephropathy
2    Metastatic Liver Cancer
Name: title, dtype: object

【讨论】:

  • 缺少“-”之前和之后的空白(因为它在包含 - 某处的诊断中失败)否则我想这是最有效的运行时解决方案......跨度>
【解决方案2】:

您可以在此处使用applylambda

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'

df = pd.DataFrame([s0, s1, s2], columns=['title'])

df['diagnosis'] = df['title'].apply(lambda x: x.split(' - ')[-1]) 

print(df['diagnosis'])

打印:

0                Pharyngitis
1                Nephropathy
2    Metastatic Liver Cancer
Name: diagnosis, dtype: object

如果你喜欢空字符串如果字符串中没有-,则将行改为:

df['diagnosis'] = df['title'].apply(lambda x: x.split(' - ')[-1] if ' - ' in x else '')

【讨论】:

  • 我不确定您是否想获取字符串,即使单元格中没有“ - ”。如果你喜欢,我已经编辑了答案
【解决方案3】:

创建一个函数来完成返回值的工作,然后将其应用于该列。

import pandas as pd

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'

def f(x):
    return x.split(" - ")[-1]

df = pd.DataFrame([s0, s1, s2], columns=['title'])
df['diagnosis'] = df['title'].apply(f) 
print(df['diagnosis'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2014-03-21
    • 2017-04-23
    • 2016-11-07
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多