所以我有一个熊猫的资料栏,叫做“年份”,里面有很多年。列如下所示:
0 1885
1 1828
2 1913
3 1906
4 1963
5 1906
6 1906
7 1903
8 1969
9 1958
10 1695
11 1889
12 1906
13 1884
14 1890
15 1873
16 1908
17 1974
18 1961
19 1963
20 1973
21 2005
22 1970
23 1852
24 1906我试图使用match()来查找格式不正确的年份。日期应该有4位数。第一个字符应该是1或2,第二个字符应该是0、7、8或9。最后两个字符应该是数字。它应该选择1695年。我还试图使用一个函数将年份转换为字符串。还有一个名为' name‘的列,我正在尝试打印与年份相同的名称(索引10)。到目前为止,这是我的代码:
y = re.match('^[3-9][1-6]*\d', df['year']).group()
def string(y):
return str(y)
string(y)任何帮助都是非常感谢的,我对正则表达式很陌生,并且已经坚持了几个小时了。谢谢。
发布于 2020-10-15 03:59:09
您可以在这里修改正则表达式,并使用熊猫.str.match系列方法应用该方法:
# bad_date_mask is a boolean array,
# where True means we have a "good" date, and False is a "bad" date
bad_date_mask = df["year"].astype(str).str.match("^[12][0789]\d\d$")
print(df.loc[bad_date_mask])
year
10 1695regex细分:
^:字符串必须以该symbol[12]:匹配字符1之后的内容开始,或者2[0789]:匹配字符0、7、8,9\d{2}:匹配任何连续的digits$:字符串必须现在结束。如果继续,则不匹配。发布于 2020-10-15 02:06:20
我的建议是: 1)拆分它,2)除非需要,否则不要使用regex。让我们创建一个布尔掩码,然后查找满足所有条件的行:
# Dates should have 4 digits
cond1 = (df.year.str.len() == 4)
# The first character should be a 1 or 2
cond2 = df.year.str.get(0).isin(("1","2"))
# The second a 0, 7, 8 or 9
cond3 = df.year.str.get(1).isin(("0","7","8","9"))
# The last two characters should be digits
cond4 = df.year.str[-2:].str.isnumeric()
joint_cond = cond1 & cond2 & cond3 & cond4
solution = df[joint_cond]建议的临界值将不返回值1695。
https://stackoverflow.com/questions/64363711
复制相似问题