簡體   English   中英

計算數據框列中的位數

[英]Count the number of digits in a dataframe column

我有一個 email_alias 列,我想使用 Python 在另一列中查找該列(每行)中的整數數。 到目前為止,我只能計算整個列中的數字總數。

試圖

我試過: df['count_numbers'] = sum(c.isdigit() for c in df['email_alias'])

示例

email_alias       count_numbers
thisisatest111      3
testnumber2         1

您可以apply自定義 Python 函數應用於該列。 我不認為有一種矢量化的方式。 sum()在這里利用了bool 是 int 的子類這一事實,因此所有True值都等於1

import pandas as pd

def count_digits(string):
    return sum(item.isdigit() for item in string)

df = pd.DataFrame({'a': ['thisisatest111', 'testnumber2']})
df['counts'] = df['a'].apply(count_digits)

你的方法:

df['count_numbers'] = sum(c.isdigit() for c in df['email_alias']) 

無法工作,因為df['count_numbers'] =對該列中每個值的賦值。 在這里, apply隱式迭代行(但在 Python 時間,所以它不是矢量化的)。 再說一次,Pandas 的大多數.str訪問器方法也是如此,盡管語法表明它會比for循環更快。

我相信這可能是最簡單的解決方案。

df['count_numbers'] = df['email_alias'].str.count('\d')

暫無
暫無

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

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