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()