Thursday, August 1, 2019

Concatenating Rows in Python Pandas

The groupby function can be used to concatenate data from multiple rows into one field.


Create a Dataframe

import pandas as pd
import numpy as np

#Create a Dictionary of series
d = {'Name': pd.Series(['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine',
   'Rahul','David','Andrew','Ajay','Teresa']),
   'Age': pd.Series([26,27,25,24,31,27,25,33,42,32,51,47]),
   'Score': pd.Series([89,87,67,55,47,72,76,79,44,92,99,69])}
 
#Create a DataFrame
df = pd.DataFrame(d)
df

the resultant dataframe will be




Now lets group by age of the student name


final_df = df.groupby('Age')['Name'].apply(', '.join)

final_df


the result will be


0 comments:

Post a Comment