簡體   English   中英

在多列上迭代和應用正則表達式函數/str 計數

[英]Iterating and Applying Regex functions/str counts over multple columns

我是 python 的新手,並試圖改進這個測試 df。 我能夠應用正則表達式 function 來查找單元格中的模式,然后向我提供單個列級別上有多少個 1 的計數。 下面是將 function 單獨應用於列的原始和結果 df 的圖像,以及各個列的代碼。 下面也是測試 df 的文本版本(圖像中缺少一行以使其更容易共享/圖像與測試 df 不匹配,但結果相似):

import pandas as pd
        
df = pd.DataFrame([["1 | | Had a Greeter welcome clients 1     | | Take measures to ensure a safe and organized distribution 1         | | Protected confidentiality of clients (on social media, pictures, in conversation, own congregation members receiving assistance, etc.)",
                    "1  | | Chairs for clients to sit in while waiting 1     | | Take measures to ensure a safe and organized distribution"],
                   ["1 | Financial literacy/budgeting 1 | | Monetary/Bill Support 1    | | Mental Health Services/Counseling",
                    "1| | Clothing Assistance 1  | | Healthcare 1    | | Mental Health Services/Counseling 1     | | Spiritual Support 1      | | Job Skills Training"]
                    ] , columns = ['CF1', 'CF2'])

原始圖案

結果DF

pattern = re.compile(r'\d+') 
df['CF1test'] = df['CF1'].apply(lambda x: '_'.join(pattern.findall(x))).str.count(pattern) 
df['CF2test'] = df['CF2'].apply(lambda x: '_'.join(pattern.findall(x))).str.count(pattern)

這是我試圖開發的循環示例,以迭代並將相同的 function 應用於多個列:

for column in df:
    df[column] = df.join([column](df.apply(lambda x: '_'.join(pattern.findall(x))).str.count(pattern), rsuffix = '_test'))

但是,我收到“TypeError:預期的字符串或類似字節的對象”,我迷路了。 有沒有更好的方法可用? 任何建議都會很棒!

您可以stack您的 dataframe 並將extractall與您的模式一起使用:

(df.stack().str.extractall('(\d+)')[0]
   #.astype(int)  # conversion to int is only required for other operations, like sum
   .groupby(level=[0,1]).count().unstack())

output:

   CF1  CF2
0    3    2
1    3    5

注意。 我在這里計算數字(任何數字,所以“test123”中的“42”或“123”也會被計算在內),如果你只想限制為 1,你可以調整正則表達式,如果你願意,你也可以執行其他操作,例如求和而不是計數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM