簡體   English   中英

熊貓查詢語句中的布爾邏輯

[英]Boolean Logic Inside Pandas Query Statement

我有以下數據.merge 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')

我懂了

        Date_x  Invoice_x         Name  Price_x Coupon_x Location_x  \
1   2017-12-24   700349.0     John Doe    59.95     NONE      VAGG1
2   2017-12-24   700349.0     John Doe    59.95     NONE      VAGG1
4          NaN        NaN  Sue Simpson      NaN      NaN        NaN

         Date_y  Invoice_y  Price_y  Coupon_y  Location_y
1   2017-12-24      800345    17.95   CHANGE    VAGG1
2   2017-12-24      800342     9.95   GADSLR    VAGG1
4   2017-12-23      800329    34.95   GADSLR    GG2

這接近我想要的。 可以通過.drop.rename刪除多余的列。 真正缺少的是能夠刪除僅出現名稱的行的功能。

我一直在沿着查詢語句中的以下幾行嘗試邏輯:

 ds =ds.query('Price_x != Price_y & Name > 1')

導致以下錯誤:

TypeError: '>' not supported between instances of 'str' and 'int'

編輯:

ds = ds[(ds[Price_x] != ds[Price_y])  &  (ds['Name'].value_counts() > 1)]

結果是:

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是空的。

Empty DataFrame
Columns: [Date_x, Invoice_x, Name, Price_x, Coupon_x, Location_x, Date_y, Invoice_y, Price_y, Coupon_y, Location_y]
Index: []

嘗試這個

ds = ds[ds.groupby('Name').Name.transform(len) > 1]
ds = ds.query('Price_x != Price_y')

第一行刪除僅出現一次的名稱。 請參閱此“ 刪除僅在DataFrame列中出現一次的值”以獲取更多信息。

另外,在錯誤df [Price_x]->中應為df [“ Price_x”]。 可以執行df.Price_x或df [“ Price_x”]。

您可以通過多個步驟來執行此操作:首先使用pd.value_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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM