假設我有一個資料框 df_products,如下所示:
product_id | 版本 | 月 |
---|---|---|
1111 | v1 | 一月 |
1111 | v2 | 二月 |
1111 | v2 | 一月 |
2222 | v1 | 馬爾 |
3333 | v2 | 一月 |
3333 | v2 | 十二月 |
4444 | v1 | 君 |
4444 | v1 | 一月 |
4444 | v2 | 君 |
如何過濾它以僅獲取版本列中至少有一個 v1 和一個 v2 的 product_ids?我想得到這樣的東西:
product_id |
---|
1111 |
4444 |
uj5u.com熱心網友回復:
使用集合操作:
s = df.groupby('product_id')['version'].agg(set)
out = s[s >= {'v1', 'v2'}].index.tolist()
輸出:
[1111, 4444]
uj5u.com熱心網友回復:
這里有兩種方法:
一個使用 groupby 和 filter 來洗掉沒有 v1 和 v2 的組
df.groupby('product_id').filter(lambda x: all(v in x['version'].values for v in ['v1','v2']))['product_id'].unique().tolist()
另一個想法是使用資料透視表和 dropna。
df.pivot_table(index='product_id', columns='version', values='month', aggfunc=set).dropna().index.tolist()
uj5u.com熱心網友回復:
我認為您可以創建兩個額外的列v1
,v2
并將 1 標記為存在,如果不使用則標記為 0
df['v1'] = 0
df.loc[df['version'] == 'v1', 'v1'] = 1
df['v2'] = 0
df.loc[df['version'] == 'v2', 'v2'] = 1
然后你可以使用 loc 來生成你需要的結果
result = df.loc[(df['v1'] == 1) & (df['v2'] == 1)]
最后,如果您不想要除錯列,請洗掉它們
df = df.drop(columns=['v1', 'v2'])
uj5u.com熱心網友回復:
這是一種方法
# values that should exist
v={'v1', 'v2'}
# group on product, and using transform aggregate the versions as set
# compare with the the valid list of version
# drop duplicates from the result
# return the product id
(df.loc[df.groupby(['product_id'] )['version']
.transform(lambda x: set(x) == v )]
.drop_duplicates(subset=['product_id'])['product_id'])
0 1111
6 4444
Name: product_id, dtype: int64
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518337.html
標籤:Python熊猫数据框