【问题标题】:How to search a DataFrame for a specific string using a wildcard如何使用通配符在 DataFrame 中搜索特定字符串
【发布时间】:2020-12-11 18:11:04
【问题描述】:

我有一个 DataFrame,其中有一列需要使用通配符进行搜索。我试过这个:

df = pd.read_excel('CHQ REG.xlsx',index=False)
df.sort_values(['CheckNumber'], inplace=True)
df[df.CheckNumber.str.match('888')]
df

这会返回 df 中的所有内容

这是我的目标:

CheckBranch  CheckNumber
  Lebanon      8880121

示例:

CheckBranch     CheckNumber
  Texas            4782436
  Georgia          8967462
  Lebanon          8880121
  China            8947512

【问题讨论】:

  • 通配符的含义是什么,如果您删除*,匹配已经适用于任何以888开头的字符串
  • 所以我删除了正确调用 dropna 时遇到的错误,但是当我运行 match('888') 时,它会显示 df 中的所有行。
  • 添加您的 df 样本,以及预期输出和当前输出
  • 我在上面发布了一些示例和预期。

标签: python pandas dataframe wildcard na


【解决方案1】:

试试:

res = df[df['CheckNumber'].astype('string').str.match('888')]
print(res)

输出

  CheckBranch  CheckNumber
2     Lebanon      8880121

作为替代方案:

res = df[df['CheckNumber'].astype('string').str.startswith('888')]

【讨论】:

  • 是的,它起作用了,但是 astype 有什么作用?我假设 .str.match 告诉 python 寻找一个字符串?
  • astype 将系列转换为字符串类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多