簡體   English   中英

如何將 dataframe 部分行分組到 pandas groupby 中的列表中

[英]How to group dataframe parts of rows into list in pandas groupby

我看到了這個頁面, How to group dataframe rows into list in pandas groupby但是,這不是我需要的。

請看我的數據表示例。

指數 專欄 1 專欄2
0 蘋果 紅色的
1個 香蕉 一種
1個 香蕉 b
2個 葡萄
2個 葡萄 那是
2個 葡萄 偉大的
2個 葡萄 水果!
3個
3個
...很多數據... ...很多數據... ...很多數據...

我只想對索引 2~3 進行分組(我需要范圍,因為我的真實數據是 hudge。)

所以我想要這張桌子

. 專欄 1 專欄2
0 蘋果 紅色的
1個 香蕉 一種
1個 香蕉 b
2個 葡萄 哇,那是很棒的葡萄果實!
3個 不好了
...很多數據... ...很多數據... ...很多數據...

我怎樣才能得到這個?

讓我們根據index列過濾 dataframe,然后對過濾后的 dataframe 進行分組。

m = df['index'].isin([2,3])

out = (pd.concat([df[~m],
                  (df[m].groupby('column1', as_index=False)
                   .agg({'index': 'first', 'column2': ' '.join}))], ignore_index=True)
       .sort_values('index', ignore_index=True))
print(out)

   index column1                   column2
0      0   apple                       red
1      1  banana                         a
2      1  banana                         b
3      2   grape  wow that's great fruits!
4      3   melon                     oh no

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM