[英]Drop consecutive duplicates in Pandas dataframe if repeated more than n times
[英]Python Pandas: How to exclude rows that have any value repeated more than n times
當談到 Python 時,我很綠色,所以如果這是一個明顯的問題,我很抱歉。
我有一個有 8 列的 dataframe。 對於每一行,前四列是單個名稱。 以下四列是與這些名稱中的每一個相關聯的位置。 這是一個例子。
名稱1 | 名稱2 | 名稱3 | 名稱4 | 位置1 | 位置2 | 位置 3 | loc4 |
---|---|---|---|---|---|---|---|
喬 | 戴夫 | 亞倫 | 亞歷克斯 | 紐約市 | 氣 | 人工神經網絡 | 法爾 |
埃里卡 | 阿拉娜 | 史蒂夫 | 布萊克 | JAX | 米婭 | JAX | JAX |
史黛西 | 湯姆 | 南希 | 斯蒂芬 | 囊 | SFR | 達爾 | 達爾 |
我想要做的就是采用 dataframe 並創建一個新的,顯示所有相同的信息,但不包括在最后 4 列中具有兩個以上相同位置的任何行。 然后結果需要重置索引。 所以上面例子的結果是:
名稱1 | 名稱2 | 名稱3 | 名稱4 | 位置1 | 位置2 | 位置 3 | loc4 |
---|---|---|---|---|---|---|---|
喬 | 戴夫 | 亞倫 | 亞歷克斯 | 紐約市 | 氣 | 人工神經網絡 | 法爾 |
史黛西 | 湯姆 | 南希 | 斯蒂芬 | 囊 | SFR | 達爾 | 達爾 |
我試圖讓它與 apply、groupby 和 count 的組合一起工作,但無法讓它正常工作。 我覺得有一個簡單的解決方案。
非常感謝!
您可以在每一行上使用nunique
:
df[df[['loc1', 'loc2', 'loc3', 'loc4']].apply(lambda x: len(x) - x.nunique() < 2, axis=1)].copy().reset_index()
嘗試這個:
df[df.filter(like = 'loc').nunique(axis = 1) > 2]
Output:
name1 name2 name3 name4 loc1 loc2 loc3 loc4
0 Joe Dave Aaron Alex NYC CHI ANN FAL
2 Stacy Tom Nancy Steph SAC SFR DAL DAL
Using filter
with like = 'loc'
to limit the dataframe columns to just the last four or the loc columns, then get the number of unique values with axis=1
using nunique
, the create a boolean series and with boolean filtering we can select correct行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.