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

bf1o4zei  于 2023-01-07  发布在  其他
关注(0)|答案(5)|浏览(300)

我在Pandas中做透视表,当做groupby(计算不同的观察值)时,aggfunc={"person":{lambda x: len(x.unique())}}给我带来了以下错误:'DataFrame' object has no attribute 'unique'有什么想法如何修复它?

uidvcgyl

uidvcgyl1#

DataFrame没有该方法;数据框中的列执行以下操作:

df['A'].unique()

或者,要获取带有观测数的名称(使用closedloop提供的DataFrame):

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

bttbmeg02#

使用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
jgwigjjp

jgwigjjp3#

从DF中获取〉1列的唯一组合的一个非常简单的解决方案如下:

unique_A_B_combos = df[['A', 'B']].value_counts().index.values
dddzy1tm

dddzy1tm4#

df[['col1', 'col2']].nunique()

尝试使用此函数而不是单独函数

csga3l58

csga3l585#

如果您只想知道存在于整个DataFrame(包括所有列)中的唯一值,您可以用途:

import numpy as np

...

np.unique(df.values)

相关问题