Pandas'DataFrame'对象没有属性'unique'

the*_*eth 4 python pivot-table pandas

我正在做pandas做数据透视表,当做groupby时(计算不同的观察结果) aggfunc={"person":{lambda x: len(x.unique())}}给我以下错误: 'DataFrame' object has no attribute 'unique' 任何想法如何修复它?

Ale*_*der 15

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

df['A'].unique()
Run Code Online (Sandbox Code Playgroud)

或者,获取具有观察数量的名称(使用closedloop给出的DataFrame):

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


clo*_*oop 8

不要在数据透视表过程中删除重复项,而是使用该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')
Run Code Online (Sandbox Code Playgroud)

这正确输出

c1  0  1
c0      
0   1  1
1   1  1
Run Code Online (Sandbox Code Playgroud)