我有一个python dataframe,其中有一个字符串列,我想将它分成多个列。
DF的某些行如下所示:
COLUMN
ORDP//NAME/iwantthispart/REMI/MORE TEXT
/REMI/SOMEMORETEXT
/ORDP//NAME/iwantthispart/ADDR/SOMEADRESS
/BENM//NAME/iwantthispart/REMI/SOMEMORETEXT
所以基本上我想要'/NAME/‘之后的所有内容,直到下一个'/’。然而。并不是每一行都有'/NAME/iwantthispart/‘字段,如第二行所示。
我尝试过使用拆分函数,但最终得到了错误的结果。
mt['COLUMN'].apply(lambda x: x.split('/NAME/')[-1])
这只是给了我/NAME/部分之后的所有内容,在没有/NAME/的情况下,它会向我返回完整的字符串。
有没有人有什么建议或解决方案?非常感谢您的帮助!(项目符号是为了使其更具可读性,并且实际上不在数据中)。
发布于 2018-07-21 16:02:11
您可以使用str.extract
提取所选的模式,使用正则表达式:
# Generally, to match all word characters:
df.COLUMN.str.extract('NAME/(\w+)')
或
# More specifically, to match everything up to the next slash:
df.COLUMN.str.extract('NAME/([^/]*)')
这两个函数都返回:
0 iwantthispart
1 NaN
2 iwantthispart
3 iwantthispart
发布于 2018-07-21 16:16:25
无论第一个单词是不是name,这两行代码都会给出第二个单词
mt["column"]=mt["column"].str.extract(r"(\w+/\w+/)")
mt["column"].str.extract(r"(\/\w+)")
这将给出以下结果作为pandas数据帧中的一列:
/iwantthispart
/SOMEMORETEXT
/iwantthispart
/iwantthispart
如果你只对包含NAME的代码行感兴趣,这对你来说很好:
mt["column"]=mt["column"].str.extract(r"(\NAME/\w+/)")
mt["column"].str.extract(r"(\/\w+)")
这将产生以下结果:
/iwantthispart
/NaN
/iwantthispart
/iwantthispar
https://stackoverflow.com/questions/51457672
复制相似问题