簡體   English   中英

如何在熊貓列中保存 str.contains() 的總和?

[英]how to save sum of str.contains() in a pandas column?

我想保存在我的 csv_file['dialog'] 列中找到 Twilight/Sparkle/Twilight Sparkle 的次數,因為 csv_file['pony_sort'] 中的相應單元格不是 twilight。 我知道這是無效的語法,但是否有可能通過這種方式獲得我想要的東西,如果是,我可以改變什么? 謝謝!

更新:

example of data: 
pony_sort | dialog | 
--------------------
twilight  | "....twilight"
applejack | "twilight, twilight, twilight!"

在上面的這個例子中,第一行不會計算“twilight”,因為 pony_sort = twilight。 第二行的計數 = 3,因為在 pony_sort 列中沒有提到 twilight,而 twilight 被提到三次。

twilight_mentions = csv_file[csv_file['dialog'].str.contains("Twilight|Sparkle|Twilight Sparkle").sum() for i in csv_file[pony_sort] != "twilight"]

請記住series.str.contains對每一行計數一次,無論它包含多少個搜索詞。 你要找的是series.str.count

from re import IGNORECASE
twilight_mentions = (
    csv_file[csv_file['pony_sort'].ne('twilight')]['dialog']
    .str.count('twilight sparkle|twilight|sparkle', flags=IGNORECASE)
    .sum()
)

輸出

3

如果不需要,可以跳過re標志。

請注意可選模式的順序,如果您將示例模式與'twilight|sparkle|twilight sparkle'那么包含'twilight, twilight sparkle'行將返回 3 而不是 2。但是,模式'twilight sparkle|twilight|sparkle' ,嘗試在遇到twil...時找到第一個選項twilight sparkle 我不知道確切的正則表達式實現,但是,這是需要注意的。

暫無
暫無

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

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