#python #pandas #dataframe
#python #pandas #фрейм данных
Вопрос:
training_data = [
['Green',3,'Apple'],
['Yellow',3,'Apple'],
['Red',1,'Grape'],
['Red',1,'Grape'],
['Yellow',3,'Lemon']
]
def unique_values(df,col):
return set([row[col] for row in df])
unique_values(training_data,1)
output = {1,3}
Я хочу иметь возможность делать это, но с фреймом данных pandas вместо списка
Комментарии:
1. Вы можете
df.agg(pd.Series.unique)
Ответ №1:
Вы можете использовать Series.unique
для поиска уникальных значений в столбце.
Создайте фрейм данных из вашего списка следующим образом:
In [1974]: import pandas as pd
In [1975]: df = pd.DataFrame(training_data, columns = ['color', 'number', 'fruit'])
In [1986]: df
Out[1986]:
color number fruit
0 Green 3 Apple
1 Yellow 3 Apple
2 Red 1 Grape
3 Red 1 Grape
4 Yellow 3 Lemon
Тогда ваша функция выглядит следующим образом:
In [1983]: def unique_values(df,col):
...: return df[col].unique().tolist()
...:
Запустите вашу функцию следующим образом:
In [1988]: unique_values(df, 'color')
Out[1988]: ['Green', 'Yellow', 'Red']
In [1989]: unique_values(df, 'fruit')
Out[1989]: ['Apple', 'Grape', 'Lemon']
In [1990]: unique_values(df, 'number')
Out[1990]: [3, 1]
Ответ №2:
Нравится это?
>>> import pandas as pd
>>> training_data = [
... ['Green',3,'Apple'],
... ['Yellow',3,'Apple'],
... ['Red',1,'Grape'],
... ['Red',1,'Grape'],
... ['Yellow',3,'Lemon']
... ]
>>> df = pd.DataFrame(training_data, columns = ['color', 'number', 'fruit'])
>>> df.head()
color number fruit
0 Green 3 Apple
1 Yellow 3 Apple
2 Red 1 Grape
3 Red 1 Grape
4 Yellow 3 Lemon
>>> df.number.unique()
array([3, 1])
Ответ №3:
def unique_values(df,column):
return set(df[column])
Это также сработало после превращения списка во фрейм данных, спасибо вам обоим!