2017-03-16 74 views
2

我正在学习如何在python中使用熊猫来操作数据。我得到了以下脚本:df.query在Python中使用熊猫产生空结果

import pandas as pd 

df = pd.read_table("t.txt") #read in the file 
df.columns = [x.strip() for x in df.columns] #strip spaces in headers 
df = df.query('TLD == ".biz"')  #select the rows where TLD == ".biz" 
df.to_csv('t.txt', sep='\t') #write the output to a tab-separated file 

但输出文件没有记录,只有标题。当我检查使用

print.df 

之前的选择,输出是:

   TLD Length            Words \ 
0  .biz   5            ... 
1  .biz   4            ... 
2  .biz   5            ... 
3  .biz   5            ... 
4  .biz   3            ... 
5  .biz   3            ... 
6  .biz   6            ... 

所以我知道该列TLD具有与.BIZ值的行。我也试过:

>>> print(df.loc[df['TLD'] == '.biz']) 

但结果是

Empty DataFrame 

随着我的专栏

的名单什么我做错了吗?

回答

2

似乎有些空格都在那里,所以需要通过strip其删除:

print(df.loc[df['TLD'].str.strip() == '.biz']) 

df['TLD'] = df['TLD'].str.strip() 
df = df.query('TLD == ".biz"') 
+0

谢谢!出于好奇 - 你是如何认识到白色空间在那里?对我的未经训练的眼睛,它看起来都很好 – TomEus

+0

,因为你删除列中的空格,所以我认为在数据中也是这样;) – jezrael

+0

也许更简单的删除列中的空格是'df.columns = df.columns.str.strip()' – jezrael