简体   繁体   English

如何根据另一列的行值查看另一列的数据?

[英]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.

相关问题 如何基于第三列中的值将numpy数组中的数据从列/行移动到另一个 - How to move data in numpy array from column/row to another based on value in third column 根据同一行中另一列的值填充缺失值 - Fill missing value based on value from another column in the same row 在Pandas中,如何根据另一行中的另一列值更新一行中的列值 - In Pandas how to update column value in one row based on another column value in another row 如何将基于列的 dataframe 中的值添加到基于行的另一个 dataframe 中? - How do I add the value from one dataframe based on a column to another dataframe based on a row? Python Pandas:根据另一列的值更新行 - Python pandas: Updating row based on value from another column 当对应的值为NaN时,如何根据另一列中的条件从前一行获取一个值? - How to get a value from a previous row when the corresponding value is NaN based on a condition in another column? 如何根据行中的特定值和熊猫中的另一列对行进行分组? - How to group rows based on specific value in a row and another column in pandas? 如何根据行中的另一个值在 dataframe 中创建列(Python) - How to create a column in a dataframe based on another value in the row (Python) 如何根据另一列值填充空索引或空行? - How to fill empty index or empty row based on another column value? 如何根据另一列的值将行分解为多行? - How to Explode row into multiple rows based on value of another column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM