在 python 中使用 Pandas 时 df.query 产生空结果

Tom*_*Eus 2 python dataframe pandas

我正在学习如何在 python 中使用 Pandas 操作数据。我得到了以下脚本:

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
Run Code Online (Sandbox Code Playgroud)

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

print.df
Run Code Online (Sandbox Code Playgroud)

在选择之前,输出是:

             TLD  Length                                              Words  \
0       .biz           5                                                ...   
1       .biz           4                                                ...   
2       .biz           5                                                ...   
3       .biz           5                                                ...   
4       .biz           3                                                ...   
5       .biz           3                                                ...   
6       .biz           6                                                ...   
Run Code Online (Sandbox Code Playgroud)

所以我知道 TLD 列有带有 .biz 值的行。我也试过:

>>> print(df.loc[df['TLD'] == '.biz'])
Run Code Online (Sandbox Code Playgroud)

但结果是

Empty DataFrame
Run Code Online (Sandbox Code Playgroud)

带有我的列列表

请问我做错了什么?

jez*_*ael 5

似乎有一些空格,所以需要通过strip以下方式删除它们:

print(df.loc[df['TLD'].str.strip() == '.biz'])
Run Code Online (Sandbox Code Playgroud)
df['TLD'] = df['TLD'].str.strip()
df = df.query('TLD == ".biz"')
Run Code Online (Sandbox Code Playgroud)