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

标签 python pandas dataframe

我正在学习如何在 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

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

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

包含我的专栏列表

请问我做错了什么?

最佳答案

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

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

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

关于python - 在 python 中使用 pandas 时 df.query 产生空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42826742/

相关文章:

数据框列表的 Python 列表 - AssertionError

python - 如何加快 Tensorflow 2 keras 模型的推理速度?

python - pandas 按不在列表中的索引值进行多索引切片

python - 使用 python pandas 数据框的 Groupby 而不扩展列名

python - 在Python中选择满足特定条件的行之间的行

dataframe - 在 Julia 数据框中选择缺失值的行

python - Monocle 是否使用了事件驱动编程的错误示例?

python - 在 Tkinter 中捕获 "Cancel"

Python-删除字典对的比例/百分比

python - 如何在 Python Pandas Dataframe 中过滤混合数据类型对象中的字符串值