Python 如果某些列的值已更改,则筛选数据帧的行

Python 如果某些列的值已更改,则筛选数据帧的行,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框,希望获取“项目id”,以便“项目价格”不会发生变化: date date_block_num shop_id item_id item_price item_cnt_day 0 02.01.2013 0 59 22154 999.00 1.0 1 03.01.2013 0 25 2552 899.00

我有一个数据框,希望获取“项目id”,以便“项目价格”不会发生变化:

         date  date_block_num  shop_id  item_id  item_price  item_cnt_day
0  02.01.2013               0       59    22154      999.00           1.0
1  03.01.2013               0       25     2552      899.00           1.0
2  05.01.2013               0       25     2552      899.00          -1.0
3  06.01.2013               0       25     2555     1709.05           1.0
4  15.01.2013               0       25     2555     1099.00           1.0
例如,这里你应该得到221542552

所以我试着:

d = {}
for row in transactions.iterrows():
    try:
        # Let's make sure that the prices of item_id have not changed
        d[row.item_id]['item_price'] != row.item_price:
            d.pop(row.item_id, None)
    # in the other case is that the item_id is no longer a dictionary key
    except KeyError:
        d[row.item_id]['item_price'] = row.item_price
但我得到:

  File "<ipython-input-22-06e70f158952>", line 5
    d[row["item_id"]]['item_price'] != row["item_price"]:
                                                         ^
SyntaxError: invalid syntax
文件“”,第5行
d[行[“项目id”][“项目价格”]!=行[“项目价格”]:
^
SyntaxError:无效语法
有;让我们在这里使用
groupby
nunique

items = df.groupby('item_id')['item_price'].nunique()
items[items == 1].index.tolist()
# [2552, 22154]
注:项目价格最好为整数,以避免浮点不准确导致错误结果


这里有一个类似的选择:

m = df.groupby('item_id')['item_price'].transform('nunique').eq(1)
df.loc[m, 'item_id'].unique()
# array([22154,  2552])