繁体   English   中英

如何检查列的前四个字符是否为“http”?

[英]How to check if the first four characters of a column are 'http' or not?

我有一个 dataframe 像:

df['Web']

我只想检查df['Web']的前四个字符是否为'http'

我不想检查df['Web']是否为 url 格式。

以及如何使用 if 条件,例如:

if (firstfour=='http'):
   print("starts with http")
else:
   print("doesn't starts with http")

您可以使用string.startswith() 但是,您不应该认为它也会匹配https

您可以使用regex匹配 http 而不是 https。

df = pd.DataFrame({'Web': ['htt', 'http', 'https', 'www']})
df['match'] = df.Web.apply(lambda x: x.startswith('http'))

     Web  match
0    htt  False
1   http   True
2  https   True
3    www  False

正则表达式

df['match'] = df['Web'].str.match(r'^http(?!s)')


     Web  match
0    htt  False
1   http   True
2  https  False
3    www  False

使用Series.str.startswith

df['match'] = df.Web.str.startswith('http')

或者使用Series.str.contains^作为字符串的开头:

df['match'] = df.Web.str.contains('^http')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM