![](/img/trans.png)
[英]In Python Pandas, how to search if column elements contains the first 2 digits
[英]Python Pandas: How to Check if Column Value Contains 3 or More Repeated Digits
我有一個 pandas 數據框,其中包含一個列,其中包含一個字符串值列表,如下所示。 某些記錄可能具有 null 值。
+--------+
| number|
+--------+
| 78809|
+--------+
|76768888|
+--------+
| 570009|
+--------+
| 5678888|
+--------+
| |
+--------+
| test |
+--------+
我想要的是添加一個新列3_rp_nm
,它顯示每行中number
列中的值是否包含 3 個或更多重復數字。 請注意, number
列可能包含 null 甚至字符值。 在這種情況下, 3_rp_nm
中的值應該是N
。
以下是預期結果:
+--------+--------+
| number| 3_rp_nm|
+--------+--------+
| 78809| N|
+--------+--------+
|76768888| Y|
+--------+--------+
| 570009| Y|
+--------+--------+
| 5678888| Y|
+--------+--------+
| | N|
+--------+--------+
| test | N|
+--------+--------+
提前致謝。
如果沒有正則表達式,您可以定義 function 來查找正確的數字,然后使用 apply() 來更新您的數據集。
import pandas as pd
nums = [78809, 76768888, None, 570009, "dsfsd", 5678888]
def find_3_consecutive(num):
if type(num) != int:
return False
s = str(num)
sz = len(s)
for i in range(sz-2):
if s[i] == s[i+1] == s[i+2]:
return True
return False
df = pd.DataFrame(nums, columns=['number'])
df['3_rp_n'] = df['number'].apply(
lambda x: 'Y' if find_3_consecutive(x) else 'N')
print(df)
一種簡單的方法是使用帶有捕獲組和引用的正則表達式:
df['3_rp_nm'] = (df['number'].str.contains(r'(\d)\1\1', regex=True)
.map({True: 'Y', False: 'N'}))
正則表達式:
(\d) # match (and capture) a number
\1 # match again the same number
\1 # match again the same number
output:
number 3_rp_nm
0 78809 N
1 76768888 Y
2 570009 Y
3 5678888 Y
4 N
5 test N
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.