新列显示唯一行的出现次数

时间:2015-06-06 19:49:03

标签: python pandas

我正在尝试研究如何使用Pandas添加一个新列,显示唯一行的出现次数,然后删除任何重复项。不使用pandas时,我可以接近这个输出:

@interface universalRow : NSObject {

}

@property (nonatomic, weak) IBOutlet WKInterfaceLabel *mainTitle;
@property (nonatomic, weak) IBOutlet WKInterfaceLabel *subtitleLabel;

@end

或通过excel显示countif或类似的新列。有没有人在熊猫做过这件事,能帮忙吗?

1 个答案:

答案 0 :(得分:1)

您可以使用df.drop_duplicates()删除重复的行。 此外,如果您想让新的DataFrame显示哪些行重复,请调用df.duplicated()

#!/usr/bin/env python3
# coding: utf-8

import pandas as pd

# define DataFrame using same sample data
d = {'i': [1, 2, 3, 4, 5, 6, 1, 4, 9, 10 ], 'j': [4, 12, 13, 1 ,15, 16, 4, 1, 19, 20]}
df = pd.DataFrame(data=d)

# print sample DataFrame
print(df)

# print DataFrame with dropped duplicate rows
print(df.drop_duplicates())

# print DataFrame containing `True` for each duplicate row, see doc for further options
print(df.duplicated())

修改(由于评论):

定义DataFrame df后,请尝试following

df.groupby(['i', 'j']).size()

.groupby()对两列进行分组,而.size()则返回底层数据中的元素数。