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