根据派生字段过滤pandas数据帧

时间:2016-06-17 13:56:09

标签: python pandas filter dataframe ipython

我有以下查询,我执行并存储在pandas数据帧中。

SELECT 
 mn as MachineName,
 dt as DateTime,
 REGEXP_EXTRACT(path, 'Name:([\\s\\S\\w\\W]*?)Domain:') AS Name1,
FROM TABLE DataGallery 

查询的输出是:

MachineName  DateTime           Name1
GOG1         2016-12-13 12:14   PI1
GOG1         2016-12-14 13:12   PI2

我正在尝试根据df [“Name1”] =“PI1”过滤数据帧。但这似乎没有成功。我尝试使用像“MachineName”和“DateTime”这样的表中的直接字段,它完全正常。

不确定此过滤是否不适用于基于REGEXP_EXTRACT的派生字段。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果需要过滤器df,则IIUC使用boolean indexing

df = pd.DataFrame({'Name1': {0: 'PI1', 1: 'PI2'}, 
                   'DateTime': {0: '2016-12-13 12:14', 1: '2016-12-14 13:12'}, 
                   'MachineName': {0: 'GOG1', 1: 'GOG1'}}
                   ,columns=['MachineName','DateTime','Name1'])

print (df)
  MachineName          DateTime Name1
0        GOG1  2016-12-13 12:14   PI1
1        GOG1  2016-12-14 13:12   PI2

print (df.Name1 == 'PI1')
0     True
1    False
Name: Name1, dtype: bool

print (df[df.Name1 == 'PI1'])
  MachineName          DateTime Name1
0        GOG1  2016-12-13 12:14   PI1

str.contains的另一个解决方案:

print (df[df.Name1.str.contains('PI1')])

  MachineName          DateTime Name1
0        GOG1  2016-12-13 12:14   PI1

答案 1 :(得分:0)

试试这个:确保它的资本"我"不是小写' L"。

  df[df["Name1"] == "PI1"] not df[df["Name1"] = "PI1"]