简体   繁体   English

"If 语句:字符串在 Python\/pandas 中以 4 个数字开头"

[英]If statement: String starts with exactly 4 digitis in Python/pandas

I have a column of a dataframe consisting of strings, which are either a date (eg "12-10-2020") or a string starting with 4 digits (eg "4030 - random name").我有一列由字符串组成的数据框,这些字符串可以是日期(例如“12-10-2020”)或以 4 位数字开头的字符串(例如“4030 - 随机名称”)。 I would like to write an if statement to capture the strings which are starting with 4 digits, which is similar to this code:我想编写一个 if 语句来捕获以 4 位数字开头的字符串,这类似于此代码:

string[0].isdigit()

使用str.contains<\/code> : col"

df[df["col"].str.contains(r'^[0-9]{4}')]

You can use str.match<\/code><\/a> that is anchored by default to the start of the string:您可以使用默认锚定到字符串开头的str.match<\/code><\/a> :

Example:例子:

df = pd.DataFrame({'col': ['4030 - random name', 'other', '07-02-2022']})

df[df['col'].str.match('\d{4}')]

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

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