查找2列的所有值

时间:2019-05-24 11:50:35

标签: python

我有以下数据框:

Name      class
John      1  
John      1 
Mayank    2  
Mayank    2  
Harshil   3   
Harshil   3  
Harshil   3

在这种情况下,输出将类似于: 课

Name      class 
John       1     
Mayank     2
Harshil    3

1 个答案:

答案 0 :(得分:0)

选择所需的解决方案。

列表

data = [('John', 1), ('John',1), ('Mayank', 2), ('Mayank', 2), ('Harshil', 3), ('Harshil', 3), ('Harshil', 3)]
data = list(set(data))
print (data)
  

[('Mayank',2),('Harshil',3),('John',1)]

词典

data = [('John', 1), ('John',1), ('Mayank', 2), ('Mayank', 2), ('Harshil', 3), ('Harshil', 3), ('Harshil', 3)]
data = {d[0]:d[1] for d in data}
print(data)
  

{'约翰':1,'玛雅克':2,'哈什尔':3}

DataFrame

import pandas as pd

data = [('John', 1), ('John',1), ('Mayank', 2), ('Mayank', 2), ('Harshil', 3), ('Harshil', 3), ('Harshil', 3)]
df = pd.DataFrame(data, columns=['name','class']).set_index('name')
df = df.drop_duplicates()
print(df)
  

名称类别
  约翰福音1
  Mayank 2
  哈什希尔3