[英]Convert values in a column to a single row Python
I have a pandas dataframe that looks like this: 我有一个看起来像这样的熊猫数据框:
Area1 Area2
1 2
1 4
1 5
1 9
2 8
2 16
2 4
2 1
3 8
3 9
How can I convert 'Area2' column so that it becomes a list of values for each 'Area1' column 如何转换“ Area2”列,使其成为每个“ Area1”列的值列表
So the output I would want is: 所以我想要的输出是:
Area1 Area2
1 2, 4, 5, 9
2 8, 16, 4, 1
3 8, 9
I have done this in R previously: 我以前在R中完成过此操作:
df %>% group_by(Area1) %>% summarise(Area2= toString(sort(unique(Area2))))
I have been trying out groupby() and agg() but have had no success. 我一直在尝试groupby()和agg(),但是没有成功。
Could someone explain what I can use once I have grouped the data using df.groupby('Area1') 当我使用df.groupby('Area1')对数据进行分组后,有人可以解释一下我可以使用什么
Many thanks in advance for any suggestions. 非常感谢您的任何建议。
You can groupby and apply list 您可以分组并应用列表
import pandas as pd
df=pd.read_csv("test.csv")
df.groupby('Area1')['Area2'].apply(list)
The R snippet does string concatenation. R代码段执行字符串连接。
The following line keeps the original type of Area2
. 以下行保留了
Area2
的原始类型。
import pandas as pd
df.groupby('Area1').Area2.apply(pd.Series.tolist).reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.