[英]How to view data from another column based on row value of another?
I have a dataframe:我有一个 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.
例如,我想打印名称“Alex”等的所有年龄值。 I tried parsing through the Name values, which are unique, so in the end I would print:
我尝试解析唯一的 Name 值,所以最后我会打印:
Alex: 10,11,8
Bob: 12,14
Clarke: 13
How can I print the age values for each unique Name of the dataframe?如何打印 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 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:基于上面 Ade_1 的回答,您可以使用以下代码格式化 output 以符合您的要求:
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: output 将是:
Alex: 10, 11, 8
Bob: 12, 14
Clarke: 13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.