Pandas“DataFrame”对象没有“unique”属性

2024-04-28 16:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫公司工作,做数据透视表和groupby(计算不同的观察结果) aggfunc={"person":{lambda x: len(x.unique())}}给出以下错误: 'DataFrame' object has no attribute 'unique' 有什么解决办法吗?


Tags: 数据lambdanodataframelenobject错误公司
2条回答

不要在透视表过程中删除重复项,而是使用df.drop_duplicates()函数有选择地删除重复项。

例如,如果使用这些index='c0'columns='c1'旋转,那么这个简单的步骤会产生正确的计数。

在本例中,第5行是第4行的副本(忽略非透视c2

import pandas as pd
data = {'c0':[0,1,0,1,1], 'c1':[0,0,1,1,1], 'person':[0,0,1,1,1], 'c_other':[1,2,3,4,5]}
df = pd.DataFrame(data)
df2 = df.drop_duplicates(subset=['c0','c1','person'])
pd.pivot_table(df2, index='c0',columns='c1',values='person', aggfunc='count')

这将正确输出

c1  0  1
c0      
0   1  1
1   1  1

DataFrames没有该方法;DataFrames中的列:

df['A'].unique()

或者,使用closedloop提供的数据帧来获取具有观察次数的名称:

>>> df.groupby('person').person.count()
Out[80]: 
person
0         2
1         3
Name: person, dtype: int64

相关问题 更多 >