Pandas - Удалить повторяющиеся значения в каждом столбце - PullRequest
2 голосов
/ 16 июня 2020

У меня есть следующий набор данных:

   **Fruit  Animal  Color    City** 
    Apple   Dog     Yellow   Paris
    Apple   Dog     Blue     Paris
    Orange  Dog     Green    Paris
    Grape   Dog     Pink     Paris
    Orange  Dog     Grey     NY
    Peach   Dog     Purple   Rome

Я хотел бы использовать pandas для удаления повторяющихся данных в каждом столбце (а не во всей строке).

Пример вывода :

**Fruit     Animal  Color    City** 
    Apple   Dog     Yellow   Paris
    Grape           Paris    NY
    Orange          Green    Rome
    Peach           Pink     
                    Grey     
                    Purple

С уважением,

Ответы [ 2 ]

1 голос
/ 16 июня 2020

Мы можем unique

s=df.T.apply(pd.Series.unique,1)
newdf=pd.DataFrame(s.tolist(),index=s.index).T
newdf
Out[57]: 
  **Fruit Animal   Color City**
0   Apple    Dog  Yellow  Paris
1  Orange   None    Blue     NY
2   Grape   None   Green   Rome
3   Peach   None    Pink   None
4    None   None    Grey   None
5    None   None  Purple   None
0 голосов
/ 16 июня 2020

вы можете попробовать столбец за столбцом, используя drop_duplicates:

for x in df.columns:
    df[x] = df[x].drop_duplicates().reset_index(drop=True)
#output:
    Fruit   Animal  Color   City
0   Apple   Dog     Yellow  Paris
1   Orange  NaN     Blue    NY
2   Grape   NaN     Green   Rome
3   Peach   NaN     Pink    NaN
4   NaN     NaN     Grey    NaN
5   NaN     NaN     Purple  NaN
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...