繁体   English   中英

带有pandas数据框和列名称作为输入的Python函数

[英]Python function with pandas dataframe and column name as inputs

我正在尝试编写一个函数,该函数采用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()

但是,我收到错误消息:

AttributeError: module 'pandas' has no attribute 'df'

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

我认为有可能使用unique和调用sorted

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

或转换为setlist和call sorted

def list_col(df, col):
    return sorted(list(set(df[col])))

样品

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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM