简体   繁体   English

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

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

I have a dataframe like:我有一个 dataframe 像:

df['Web']

I just want to check the first four characters of df['Web'] is 'http' or not.我只想检查df['Web']的前四个字符是否为'http'

I don't want to check if df['Web'] is in url format or not.我不想检查df['Web']是否为 url 格式。

And how to use if condition like:以及如何使用 if 条件,例如:

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

You can use string.startswith() .您可以使用string.startswith() However you should not that it would also match https as well.但是,您不应该认为它也会匹配https

You could use regex to match http and not 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

Regex正则表达式

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


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

Use Series.str.startswith :使用Series.str.startswith

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

Or use Series.str.contains with ^ for start of string:或者使用Series.str.contains^作为字符串的开头:

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

暂无
暂无

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

相关问题 在Key中按前四个字符对Python Dictionary进行排序 - Sort Python Dictionary by first four characters in Key 如何创建一个 DataFrame,其中最后一列(即第五列)将是前四列的相加 - How to create a DataFrame in which last column (i.e. fifth column) will be the addition of first four column 编辑要求输入用户名的程序。 它应该检查前四个字符是字母,第五和第六个字符是数字。 在 Python 中 - Edit your program which asks for a username. It should check that the first four characters are alpha and the fifth and sixth are digits. IN PYTHON 连接四个游戏时,更容易检查四行/列/对角线? - Easier way to check for four in row/column/diagonal in connect four game? 如何检查连接四中的对角线 - How to Check Diagonals in Connect Four 如何在其他四个数据框的列中检查一个或哪些数据帧列可用? - How to check one dataframe column available or not in other four dataframe's column? 如何在不使用循环的情况下将 dataframe 的前四行转换为列名? - How to transform first four rows of dataframe to column names without using loop? 如何根据列名的前三个字符更改列名 - How to change column names based on the first three characters of the column name 删除列表中字符串的前四个和后四个字符,或删除特定的字符模式 - removing first four and last four characters of strings in list, OR removing specific character patterns 如何检查输入是否在矩阵的第一列内 - How to check if the input is within the first column of the matrix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM