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]
after the process:
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:
Thanks in advance.
You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.
To concatenate strings from several rows using Python Pandas groupby, we can use the transform method. to create the text column that calls groupby on the selected columns name and month . And then we get the text column from the grouped data frame and call transform with a lamnda function to join the strings together.
The Hello, World! of pandas GroupBy You call . groupby() and pass the name of the column that you want to group on, which is "state" . Then, you use ["last_name"] to specify the columns on which you want to perform the actual aggregation.
Use pandas. concat() to concatenate/merge two or multiple pandas DataFrames across rows or columns. When you concat() two pandas DataFrames on rows, it creates a new Dataframe containing all rows of two DataFrames basically it does append one DataFrame with another.
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.
You want
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]
This groups the data frame by the values in column a
. Read more about groupby.
This is doing a regular list sum
(concatenation) just like [1, 2, 3] + [2, 5]
with the result [1, 2, 3, 2, 5]
df.groupby('column_a').agg(sum)
This works because of operator overloading sum
concatenates the lists together. The index of the resulting df will be the values from column_a
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With