Python 查询语句中的布尔逻辑
我有以下数据帧,Python 查询语句中的布尔逻辑,python,python-3.x,pandas,numpy,scikit-learn,Python,Python 3.x,Pandas,Numpy,Scikit Learn,我有以下数据帧,ds,它是通过.merge实现的: Date_x Invoice_x Name Coupon_x Location_x Date_y \ 1 2017-12-24 700349.0 John Doe NONE VAGG1 2017-12-24 2 2017-12-24 700349.0 John Doe NONE VAGG1 2017-12-24
ds
,它是通过.merge
实现的:
Date_x Invoice_x Name Coupon_x Location_x Date_y \
1 2017-12-24 700349.0 John Doe NONE VAGG1 2017-12-24
2 2017-12-24 700349.0 John Doe NONE VAGG1 2017-12-24
4 NaN NaN Sue Simpson NaN NaN 2017-12-23
Invoice_y Price Coupon_y Location_y
1 800345 17.95 CHANGE VAGG1
2 800342 9.95 GADSLR VAGG1
4 800329 34.95 GADSLR GG2
我要寻找的是以下内容的输出:
Date Invoice Name Coupon Location Price
1 2017-12-24 700349 John Doe NONE VAGG1 17.95
2 2017-12-24 700349 John Doe NONE VAGG1 9.95
使用以下代码:
ds = ds.query('Price_x != Price_y')
我明白了
这接近我想要的。可以通过.drop
和.rename
删除额外的列。真正缺少的是能够去掉名称只出现一行的行
我在查询语句中尝试了以下几行逻辑:
ds =ds.query('Price_x != Price_y & Name > 1')
这将导致以下错误:
TypeError: '>' not supported between instances of 'str' and 'int'
编辑:
其结果是:
NameError: name 'Price_x' is not defined
或者,尝试:
ds = ds[(ds.Price_x != ds.Price_y) & (ds['Name'].value_counts() > 1)]
导致
c:\users\...\python\python36\lib\site-packages\pandas\core\indexes\base.py:3140: RuntimeWarning: '<' not supported between instances of 'int' and 'str', sort order is undefined for incomparable objects
return this.join(other, how=how, return_indexers=return_indexers)
C:\Users\...\Python\Python36\Scripts\ipython:1: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
试试这个
ds = ds[ds.groupby('Name').Name.transform(len) > 1]
ds = ds.query('Price_x != Price_y')
第一行删除只出现一次的名称。有关更多信息,请参见此
另外,在错误df[Price\u x]->中,它应该是df[“Price\u x”]。你可以选择df.Price\ux或df[“Price\ux”]。试试这个
ds = ds[ds.groupby('Name').Name.transform(len) > 1]
ds = ds.query('Price_x != Price_y')
第一行删除只出现一次的名称。有关更多信息,请参见此
另外,在错误df[Price\u x]->中,它应该是df[“Price\u x”]。您可以使用df.Price\u x或df[“Price\u x”]。您可以通过多个步骤来完成此操作:首先使用
pd.value\u counts
来计算每个名称的发生次数,然后将其与原始数据合并并查询。例如:
counts = pd.value_counts(ds.Name).reset_index()
counts.columns = ['Name', 'Name_count']
ds.merge(counts, on='Name').query('Price_x != Price_y & Name_count > 1')
您可以通过多个步骤来完成此操作:首先使用
pd.value\u counts
来计算每个名称的发生次数,然后将其与原始数据合并并查询。例如:
counts = pd.value_counts(ds.Name).reset_index()
counts.columns = ['Name', 'Name_count']
ds.merge(counts, on='Name').query('Price_x != Price_y & Name_count > 1')
你期望的输出是什么?当你说“去掉只出现一个名称的行”是什么意思?
df.query(“…”).groupby(by=[…]).filter(lambda g:g.shape[0]>1)
@jakevdp我表达了我在第二个代码块中寻找的内容。”我要找的是“@PaulH”的输出你有没有可能把整行作为答案?你想要的输出是什么?当你说“去掉只出现一个名称的行”是什么意思?df.query(“…”).groupby(by=[…]).filter(lambda g:g.shape[0]>1)
@jakevdp我表达了我在第二个代码块中寻找的内容。”我要找的是“@PaulH”的输出你有没有可能把整行作为答案?
counts = pd.value_counts(ds.Name).reset_index()
counts.columns = ['Name', 'Name_count']
ds.merge(counts, on='Name').query('Price_x != Price_y & Name_count > 1')