我有一个数据框与这些数据。
将熊猫作为 pd 导入
Data = {'item': ['2','1','2'],
“可用”: [“真” 、 “假”]}
Df = pd.DataFrame (数据)
================================
项目 | 可用
---------------------
2 | 真
1 | False
2 | 假
在数据帧中,我有如上所示的数据。正如你所看到的,我对项目 2 既有真也有假。在这种情况下,我想要一个只有真的记录。
预期输出:
项目 | 可用
---------------------
2 | 真
1 | False
请帮助编写使用 python pandas 的条件。
谢谢
I think you need first replace strings True and False to boolean if necessary and then get first row with True per groups by DataFrameGroupBy.idxmax for indices and selecting by DataFrame.loc:
Df ['isavailable'] = df ['isavailable']。地图 ({'True': True,'False': False})
Df = df.loc [df.groupby ('item',sort = False) ['isavailable'].idxmax ()]
打印 (df)
项目可用
0 2 真
1 1 假
Since bool is also kind of int:
Df = df.Sort _ values ('isavailable').drop_duplicates (子集 = ['item'],keep = 'last')
当然,这将会重新订购你的物品。
Here is a solution where we check if the value True is one of the values assigned to each item. If so, the outcome is also True.
> Df.groupby (['item']) ['isavailable'].apply (λ x: x 中的 True)
项目
1 真
2 假
名称: IsAvailable,dtype: bool
如果要保留列名,请使用
> Df.groupby (['item']) ['isavailable']。应用 (λ x: x 中的 True)。reset _ index ()
项目可用
0 1 真
1 2 假