问题描述
我有一个数据框df,有两列,我想将一列分组并加入属于同一组的列表,例如:
I have a dataframe df, with two columns, I want to groupby one column and join the lists belongs to same group, example:
column_a, column_b
1, [1,2,3]
1, [2,5]
2, [5,6]
此过程之后:
column_a, column_b
1, [1,2,3,2,5]
2, [5,6]
我想保留所有重复项.我有以下问题:
I want to keep all the duplicates. I have the following questions:
- 数据框的dtype是对象. convert_objects()不会自动将column_b转换为列表.我怎样才能做到这一点?
- df.groupby(...).apply(lambda x:...)中的函数适用于什么? x的形式是什么?列表?
- 我主要问题的解决方案?
先谢谢了.
推荐答案
object
dtype是一个万能的dtype,基本上意味着不是int,float,bool,datetime或timedelta.因此它将它们存储为列表. convert_objects
尝试将列转换为这些dtype之一.
object
dtype is a catch-all dtype that basically means not int, float, bool, datetime, or timedelta. So it is storing them as a list. convert_objects
tries to convert a column to one of those dtypes.
你想要
In [63]: df
Out[63]:
a b c
0 1 [1, 2, 3] foo
1 1 [2, 5] bar
2 2 [5, 6] baz
In [64]: df.groupby('a').agg({'b': 'sum', 'c': lambda x: ' '.join(x)})
Out[64]:
c b
a
1 foo bar [1, 2, 3, 2, 5]
2 baz [5, 6]
这将根据列a
中的值对数据帧进行分组.进一步了解[groupby].( http://pandas.pydata.org/pandas-docs/stable/groupby.html ).
This groups the data frame by the values in column a
. Read more about [groupby].(http://pandas.pydata.org/pandas-docs/stable/groupby.html).
这就像[1, 2, 3] + [2, 5]
这篇关于 pandas groupby和加入名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!