I have a dataframe:
data = [['Alex',10],['Alex',11],['Alex',8],['Bob',12],['Bob',14],['Clarke',13]]
df2 = pd.DataFrame(data,columns=['Name','Age'])
I want to print the age values for unique values of Names. For example, I want to print all age values for the name 'Alex' and so on. I tried parsing through the Name values, which are unique, so in the end I would print:
Alex: 10,11,8
Bob: 12,14
Clarke: 13
How can I print the age values for each unique Name of the dataframe?
for name in df2['Name'].unique():
print(name)
print(df2['Age'])
You can try this
unique = df2.groupby(by='Name')['Age'].apply(list)
for i in unique.iteritems():
print(i)
output
('Alex', [10, 11, 8])
('Bob', [12, 14])
('Clarke', [13])
Building upon Ade_1's answer above, you can format the output to match your requirements with the following code:
unique = df2.groupby(by='Name')['Age'].apply(list)
for name in unique.index:
ages = str(unique[name]).strip('[]')
print('{}: {}'.format(name, ages))
The output will be:
Alex: 10, 11, 8
Bob: 12, 14
Clarke: 13
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.