One method to combine multiple rows of a dataframe into a single value is to use the groupby()
function and specify the desired column(s) to group by. Then, use the agg()
function to apply a method, such as sum()
, mean()
, max()
, or min()
, to combine the values within each group into a single value.
For example, if we have a dataframe df
with columns name
, age
, and city
, and we want to combine the ages of individuals with the same name into a single value, we can use the following code:
grouped = df.groupby('name').agg({'age': 'sum'})
This will create a new dataframe grouped
with a single row for each unique name in the original dataframe, where the age column contains the sum of ages for all individuals with that name.
Asked: 2023-06-20 04:48:06 +0000
Seen: 9 times
Last updated: Jun 20 '23