【问题标题】:Python search string contains charactersPython 搜索字符串包含字符
【发布时间】:2021-06-12 19:34:09
【问题描述】:

我有一个数据如下:

col1      
086945159
549615853
589ac2546
GED456231
F56hy8W12

我想查找col是否有非数值并返回。

col1         col2 
086945159    086945159
549615853    549615853
589ac2546    Nan
GED456231    Nan
F56hy8W12    Nan
111111111    Nan
222222222    Nan

我使用re.search(r'[^0-9]+', str) 来查找。但是,我如何在apply() 中使用它,因为如果col 中的值具有相同的数字,例如11111111222222222,这应该返回Nan

【问题讨论】:

  • 我很确定你不能用正则表达式检查字符串是否包含相同的值。所以我建议之后用nan 替换它。
  • 嗨!我相信社区可以帮助你解决这个问题。但首先,请使用tour,阅读what's on-topic here、如何提问和question checklist,并提供minimal reproducible example。 “为我实现此功能”与此站点无关。你必须做出诚实的尝试,然后就你的算法或技术提出一个具体的问题。欢迎使用 Stack Overflow!
  • 你可以检查 len(set(string.split())) == 1

标签: python regex pandas data-manipulation re


【解决方案1】:

您可以将mask 与条件模式一起使用:

# first part to match any non-digit
# second part to match identical characters
df['col2'] = df.col1.mask(df.col1.str.contains(r'\D|^(.)\1*$'))

输出:

        col1       col2
0  086945159  086945159
1  549615853  549615853
2  589ac2546        NaN
3  GED456231        NaN
4  F56hy8W12        NaN
5  111111111        NaN
6  222222222        NaN

【讨论】:

  • 我想我的评论有误。今天学到了新东西,谢谢
  • 这里的\D|^(.)\1*$ 是什么意思?
  • @PeterChen 请参阅explanation here
  • 是否可以将Nan 返回为" """
  • 链与fillna('')?
猜你喜欢
  • 1970-01-01
  • 2019-05-17
  • 2013-06-26
  • 2013-11-10
  • 2011-05-25
  • 2019-07-08
  • 1970-01-01
  • 2020-05-01
  • 2023-02-02
相关资源
最近更新 更多