実現したいこと
groupbyで分けたdataframeを一行ずつ取得したいです。
やったこと
以下のようにdataframeのカラム「col1」でgroupbyしてデータを分けました。
ここからさらに一行ずつ取り出したいです。
python
1import pandas as pd 2df = pd.DataFrame( 3 data={'col1': [10, 10, 30, 30], 4 'col2': [50, 60, 70, 80], 5 'col3': ['a', 'b', 'c', 'd']}, 6 index=['row1', 'row2', 'row3', 'row4'] 7) 8 9group = df.groupby('col1') 10 11for i in group: 12 print(i) 13 14#実行結果 15 col1 col2 col3 16row1 10 50 a 17row2 10 60 b 18 19 col1 col2 col3 20row3 30 70 c 21row4 30 80 d
上記の実行結果から一行ずつ取り出すために色々してみたのですが、groupbyの返却値がタプルなのが駄目なのかうまくいきません。
どのようにすれば一行ずつ取れるでしょうか。よろしくお願いします。
python
1for name, i in group: 2 print(name) 3 print(i[0]) 4# エラー 5KeyError: 0 6The above exception was the direct cause of the following exception: 7 8for i in group.iterrows(): 9 print(i) 10# エラー 11AttributeError: 'DataFrameGroupBy' object has no attribute 'iterrows' 12

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2023/02/21 12:09
2023/02/21 12:15 編集
2023/02/21 12:17
2023/02/21 12:30