Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将函数应用于数据帧中的每一列_Python_Pandas_Dataframe_Data Science - Fatal编程技术网

Python 将函数应用于数据帧中的每一列

Python 将函数应用于数据帧中的每一列,python,pandas,dataframe,data-science,Python,Pandas,Dataframe,Data Science,我有这个: df = DataFrame(dict(person= ['andy', 'rubin', 'ciara', 'jack'], item = ['a', 'b', 'a', 'c'], group= ['c1', 'c2', 'c3', 'c1'], age= [23, 24, 19, 49])) df: age group item person 0 23 c1 a andy 1 24 c2 b ru

我有这个:

df = DataFrame(dict(person= ['andy', 'rubin', 'ciara', 'jack'], 
     item = ['a', 'b', 'a', 'c'], 
     group= ['c1', 'c2', 'c3', 'c1'], 
     age= [23, 24, 19, 49]))
df:

    age group item person
0   23  c1    a    andy
1   24  c2    b    rubin
2   19  c3    a    ciara
3   49  c1    c    jack
我想做的是得到每列中唯一项的长度。 现在我知道我可以做如下事情:

len(df.person.unique())
对于每一列

是否有一种方法可以一次完成所有列

我试着做:

for column in df.columns:
    print(len(df.column.unique()))
但我知道这是不对的

我如何才能做到这一点?

您可以使用:

for column in df:
    print(len(df[column].unique()))

4
3
3
4      
或:


您可以将每列中唯一项目的数量设置为:

for column in df.columns:
    print(len(df[column].unique()))
你想要


为什么不做这样的事情呢

df.nunique()

我是python/pandas新手,这真的很有帮助。从没想过我能做到。neat.@xen.m.rph现在你有15名代表,请随意投票。其他回答者也会很感激投票,因为他们付出了很大的努力来帮助你。
df.apply(pd.Series.nunique)

age       4
group     3
item      3
person    4
dtype: int64
df.nunique()