簡體   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