Python函数,以pandas数据帧和列名作为输入

Cap*_*hes 1 python attributes dataframe pandas

我正在尝试编写一个函数,它将Pandas DataFrame(df)和列名(col)作为输入,并按排序顺序返回列中所有唯一值的列表.我试图在没有任何模块方法的情况下这样做.

我使用以下代码:

import pandas as pd

def list_col(df, col):
    """puts unique items of given column in a list"""
    f = pd.df()
    l = []
    r = f.loc[:,col]
    for i in r:
        if i not in l:
            l.append(i)
        return l.sort()
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误消息:

AttributeError: module 'pandas' has no attribute 'df'
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?谢谢!

jez*_*ael 5

我认为有可能使用unique和致电sorted:

def list_col(df, col):
    return sorted(df[col].unique())
Run Code Online (Sandbox Code Playgroud)

或转换为set,list并致电sorted:

def list_col(df, col):
    return sorted(list(set(df[col])))
Run Code Online (Sandbox Code Playgroud)

样品:

df = pd.DataFrame({'A':list('ddcdef'),
                   'B':[4,5,4,5,5,4],
                   'F':list('acabbb')})

print (df)
   A  B  F
0  d  4  a
1  d  5  c
2  c  4  a
3  d  5  b
4  e  5  b
5  f  4  b

def list_col(df, col):
    return sorted(df[col].unique())

print (list_col(df, 'F'))
['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)