LoginSignup
1
0

More than 1 year has passed since last update.

Python: C# の GroupBy(g=> g).Where(w=> w.Count() == 2) の実現方法

Last updated at Posted at 2021-11-24

背景

Python だと全然よくわからず・・調べた記録

C#-LINQでの取得方法
list.GroupBy(g=> g).Where(w=> w.Count() == 2)

python は書きやすいと思っていたので、Linq のような簡単な方法があるんじゃないのかなぁ・・と思い調べたが見つからず・・

試行

groupby

普通にこれでやれると思ったら、思ったように取得出来なかった・・
使い方が悪いのかと試行錯誤したあとで、
以下の Sample で、同一の文字列突っ込んでみたら別グループにされてしまったので、諦め

sort してないからだったらしい。再度やってみたらちゃんとでけました :laughing:

byCollection
cards = [1, 2, 5, 8, 5, 2, 2]
groups = []
cards.sort()    # sort してないと groupby は効かない
for keyword, group in groupby(cards, lambda card: card):
    currentGroup = list(group)
    if (len(currentGroup) == 2):
        groups.append(currentGroup) 

ゴリゴリ・・

結局、以下で実現。

  1. Unique Key の抽出
    1. Key で Filter
      x[1]を指定しないといけないのも感覚的じゃない・・
      items() → values() で不要にはなりました。@tafadfak さんありがとう :laughing:
      これ debugger で止めても分かんなかったけど、VS の intelisence なら出るのかな?
  2. 中身の長さで Filter
byCollection_二版
cards = [1, 2, 5, 8, 5, 2, 2]
groupedValues = {uniqueValue:[inputValue for inputValue in cards if inputValue == uniqueValue] for uniqueValue in unique(cards)}
listPairs = filter(lambda x: len(x)==2, groupedValues.values())   
print(list(listPairs))  
byCollection_初版
cards = [1, 2, 5, 8, 5, 2, 2]
groupedValues = {uniqueValue:[inputValue for inputValue in cards if inputValue == uniqueValue] for uniqueValue in unique(cards)}
listPairs = filter(lambda x: len(x[1])==2, groupedValues.items())    # x[0]: Index, x[1]: value(s) 
print(list(listPairs))  

取得結果

[(5, [5, 5])]

pandas

ちょっと諦めきれなかったので、調査中に見つけた有名な Library で試してみた。
ゴリゴリのよりは、まだ分かりやすい・・。でも、groupby の指定がなんか感覚的に違和感・・
基本的に行列の処理用だから、Column 名や Index でグルーピングなんだろうな、とは

byPandas
df = pd.DataFrame([1, 2, 5, 8, 5, 2, 2])
grouped = df.groupby([0])
print(grouped.filter(lambda x: x.size == 2))

取得結果

0
2 5
4 5

keyword

how to retreive 'groupby' when same data exists in the list

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0