[英]New column showing number of occurrences of unique rows
我正在嘗試找出如何使用Pandas添加新列以顯示唯一行的出現次數,然后刪除所有重復行。 不使用pandas時,我可以接近此輸出:
sort <inputfile | uniq -c
或通過excel帶有顯示countif或類似內容的新列。 有沒有人在熊貓上做到這一點,請問有什么可以幫助的嗎?
您可以使用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
,請嘗試以下操作 :
df.groupby(['i', 'j']).size()
.groupby()
對這兩列進行分組,而.size()
返回底層數據中的元素數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.