pandas -提取以特定字符开头的字符串 [英] Pandas - Extract a string starting with a particular character

查看:263
本文介绍了 pandas -提取以特定字符开头的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它应该很简单,但我无法实现.

It should be fairly simple yet I'm not able to achieve it.

我有一个数据框df1,其列为"name_str".下面的示例:

I have a dataframe df1, having a column "name_str". Example below:

   name_str 
0    alp:ha
1    bra:vo
2  charl:ie

我必须创建另一列,该列包含-说5个字符-在后加冒号(:).我编写了以下代码:

I have to create another column that would comprise - say 5 characters - that start after the colon (:). I've written the following code:

import pandas as pd

data = {'name_str':["alp:ha", "bra:vo", "charl:ie"]}
#indx = ["name_1",]
df1 = pd.DataFrame(data=data)
n= df1['name_str'].str.find(":")+1
df1['slize'] = df1['name_str'].str.slice(n,2)
print(df1)

但输出令人失望:NaanN

But the output is disappointing: NaanN

   name_str  slize
0    alp:ha    NaN
1    bra:vo    NaN
2  charl:ie    NaN

输出应该是:

   name_str  slize
0    alp:ha    ha
1    bra:vo    vo
2  charl:ie    ie

有人可以帮忙吗?欣赏它.

Would anyone please help? Appreciate it.

推荐答案

您可以使用 根据您更新的问题进行编辑

如果您想在冒号后提取最多5个字符,则可以使用此修改:

If you'd like to extract up to 5 characters after the colon, then you can use this modification:

df['slize'] = df1.name_str.str.extract(':(.{,5})') 

这篇关于 pandas -提取以特定字符开头的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆