检查DataFrame或ndrray是否包含数字

时间:2018-04-11 11:18:40

标签: python pandas numpy dataframe

我坚持这几个小时: 我有一个DataFrame,其中包含一个电子邮件地址列表,我想要检查邮件中是否包含的电子邮件地址是否为I.E. roberto123@example.com,如果是,我希望将此数字附加到数组:

我已经尝试过使用DataFrame,还有ndarray woth numpy,但它不起作用。这就是我想要做的事情:

mail_addresses = pd.DataFrame(customers_df.iloc[:,0].values)
mail_addresses = mail_addresses.dropna(axis = 0, how= 'all')
mail_addresses_toArray = mail_addresses.values

for i in mail_addresses:
dates =[]
if any(i.isdigit()) == True:
    dates.append(i)
    print(dates)

我认为我的问题是我不知道如何将此数组中的所有元素转换为字符串,以便方法isdigit()可以工作并遍历内部的所有元素(825邮件地址)。

当运行上面的代码时,这是我得到的错误:

AttributeError: 'numpy.int64' object has no attribute 'isdigit'

同时,如果我尝试使用numpy数组(mail_addresses_toArray),这就是错误:

AttributeError: 'numpy.ndarray' object has no attribute 'isdigit'

3 个答案:

答案 0 :(得分:3)

如果每封邮件只包含一个numberextract,如果可能有多个邮件,请使用findall

customers_df = pd.DataFrame({'A':['roberto123@example.com','foo123@foo.com',
                                  'bar@bar.com','23re55@re.com'],
                   'B':[4,5,4,5],
                   'C':[7,8,9,4]})

print (customers_df)
                        A  B  C
0  roberto123@example.com  4  7
1          foo123@foo.com  5  8
2             bar@bar.com  4  9
3           23re55@re.com  5  4

L = customers_df.iloc[:,0].str.extract('(\d+)', expand=False).dropna().astype(int).tolist()
print (L)
[123, 123, 23]

L = np.concatenate(customers_df.iloc[:,0].str.findall('(\d+)')).astype(int).tolist()
print (L)
[123, 123, 23, 55]

答案 1 :(得分:2)

这是一种方式。

import pandas as pd

df = pd.DataFrame({'A': ['abc123@gmail.com', 'bcdef@hotmail.com',
                         'sdafasf43@abc.com', None]})

s = df['A'].dropna()

t = s.map(lambda x: ''.join([i for i in x if i.isdigit()]).strip())
res = t.loc[t != ''].map(int).tolist()

# [123, 43]

答案 2 :(得分:1)

看起来像:

a)您需要修改自己创建mail_addresses的方式。不知何故,它充满了numpy.int64个对象而不是包含电子邮件地址的字符串,就像你期望的那样。

b)一旦您对其进行了排序,您需要对每个电子邮件地址的各个字符使用.isdigit方法。目前,您一次只能在整个电子邮件地址上拨打电话。这是我的意思的一个例子:

import numpy

emails = numpy.array([
    'foo123@foo.com',
    'bar@bar.com',
    '2re23@re.com',
])

digits = []

for email in emails:
    # first we loop over each email in the array
    for c in email:
        # then we loop over each character `c` in an email
        if c.isdigit():
            digits.append(int(c))

print(digits)

输出:

[1, 2, 3, 2, 2, 3]

如果你想要整数而不是数字,你可以使用正则表达式:

import numpy
import re

numRe = re.compile('\d+')

emails = numpy.array([
    'foo123@foo.com',
    'bar@bar.com',
    '2re23@re.com',
])

digits = [int(num) for email in emails for num in numRe.findall(email)]

print(digits)

输出:

[123, 2, 23]
相关问题