In: Computer Science
How to create a compacted data set by combining the columns Old, Older, Young, Younger and place them in into one single new column called age using python pandas.
id | Test1 | Old | Older | Young | Younger |
0.1 | 1 | False | False | False | False |
0.2 | 2 | False | True | True | False |
0.3 | 3 | True | False | False | False |
0.4 | 4 | False | False | False | False |
Code:
import pandas as pd
df = pd.DataFrame({'id':[0.1,0.2,0.3,0.4],
'Test1':[1,2,3,4],
'Old':['False','False','True','False'],
'Older':['False','True','False','False'],
'Young':['False','True','False','False'],
'Younger':['False','False','False','False']
})
print("Before")
print(df.to_string(index=False))
df['age']=df.iloc[:,2:6].apply(lambda x:' '.join(x),axis=1)
print("After")
print(df.to_string(index=False))
Screenshots: