Python循环通过Dataframe' Series'对象没有属性

时间:2016-10-17 23:25:41

标签: python pandas dataframe

使用pandas版本0.19.0,我有一个带有编译正则表达式的数据帧。我想遍历数据帧,看看是否有任何正则表达式匹配一个值。我可以使用两个for循环来完成它,但我无法弄清楚如何执行它以便它返回相同大小的数据帧。

import pandas as pd
import re

inp = [{'c1':re.compile('a'), 'c2':re.compile('b')}, {'c1':re.compile('c'),'c2':re.compile('d')}, {'c1':re.compile('e'),'c2':re.compile('f')}]
df = pd.DataFrame(inp)
for i,v in df.items():
  for a in v:
    if (a.match('a')):
      print("matched")
    else:
      print("failed")

这失败了:

[a.match('a') for a in [v for i,v in df.items()]]
  

属性错误:'系列'对象没有属性'匹配'

我想要的是什么:

[a.match('a') for a in [v for i,v in df.items()]]
              c1                                         c2
0   <_sre.SRE_Match object; span=(0, 1), match='a'>     None
1   None                                                None
2   None                                                None

1 个答案:

答案 0 :(得分:2)

看起来您需要使用applymap方法。有关详细信息,请参阅文档here

df.applymap(lambda x: x.match('a'))

输出:

enter image description here