pancakes
pancakes

Reputation: 169

pandas python: how to append based on a condition of a column?

Say i have a simple data frame:

student_id    name   age   address
student1       a     12      us
student2       b     13      us
student3       c     13      uk

I want to append the values of age and address to the name if there is a condition, lets say concatenate age and address to name if age is 13, like so:

student_id    name   age   address
student1       a     12      us
student2       b     13      us
student3       c     13      uk
             b-13-us
             c-13-uk

How do I implement this to my current dataframe?

Upvotes: 1

Views: 83

Answers (1)

jezrael
jezrael

Reputation: 862511

First filter columns by DataFrame.loc and mask bySeries.eq, convert to strings and join together:

s = df.loc[df['age'].eq(13), ['name','age','address']].astype(str).agg('-'.join, 1)

Then create one column DataFrame by Series.to_frame, if want repalce all columns to empty strings add DataFrame.reindex (also age column is now mixed - numeric and strings) and add new rows by DataFrame.append

df1 = s.to_frame('name').reindex(df.columns, fill_value='', axis=1)
df = df.append(df1, sort=False, ignore_index=True)
print (df)
  student_id     name age address
0   student1        a  12      us
1   student2        b  13      us
2   student3        c  13      uk
3             b-13-us            
4             c-13-uk            

For new format is processing each column separately:

df0 = df[df['age'].eq(13)].copy()
s = df0['name'] + ' (' + df0['age'].astype(str) + '-' + df0['address'] + ')'
df1 = s.to_frame('name').reindex(df.columns, fill_value='', axis=1)
df = df.append(df1, sort=False, ignore_index=True)
print (df)
  student_id       name age address
0   student1          a  12      us
1   student2          b  13      us
2   student3          c  13      uk
3             b (13-us)            
4             c (13-uk)  

Upvotes: 3

Related Questions