将列中的值转换为单行 Python

Convert values in a column to a single row Python

我有一个 pandas 数据框,如下所示:

Area1  Area2 
  1      2      
  1      4
  1      5
  1      9
  2      8
  2      16
  2      4
  2      1
  3      8
  3      9

如何转换 'Area2' 列,使其成为每个 'Area1' 列的值列表

所以我想要的输出是:

Area1     Area2 
  1      2, 4, 5, 9     
  2      8, 16, 4, 1
  3      8, 9

我以前在 R 中做过这个:

df %>% group_by(Area1) %>% summarise(Area2= toString(sort(unique(Area2)))) 

我一直在尝试 groupby() 和 agg() 但没有成功。

谁能解释一下我使用 df.groupby('Area1')

对数据进行分组后可以使用的内容

非常感谢您提出任何建议。

可以groupby并应用list

import pandas as pd
df=pd.read_csv("test.csv")
df.groupby('Area1')['Area2'].apply(list)

R 代码片段执行字符串连接。

下面一行保留Area2的原始类型。

import pandas as pd

df.groupby('Area1').Area2.apply(pd.Series.tolist).reset_index()