Skip to main content
 首页 » 编程设计

python之来自某些列的唯一值,DF pandas

2024年10月25日9oomusou

如果我有一些 DataFrame:

A B 
1 a 
1 a 
1 b  
1 c 
1 c 
1 d 
2 a 
2 b 
2 b 
2 d 

我可以使用 groupby() 命令并计算每个唯一行中的事件数。但是现在,我不想计算所有独特的线条。我只想计算 B 列中有多少唯一值对应于 A 列中的某个值。我现在的输出应该是

A UniqueValuesFromB 
1 4 
2 3 

为此我做了下一段代码:

userNumber = [] 
items = [] 
for pos in df[column].unique(): 
        dfEvent = df[df[column] == pos] 
        userNumber.append(len(numpy.unique(dfEvent[correspondingColumn]))) 
        items.append(pos) 

然后我从新列表中创建新的新 DF... 什么是编写此片段的更好方法。特别是,我觉得我可以在这里使用 groupby() 命令或类似命令。 拜托,只要求具有强烈时间性能改进的 pythonic 方式(或某些 pandas 函数的实现)。

请您参考如下方法:

另一种使用value_counts的方法,这里的关键是将级别数传递给count:

In [32]: 
 
df.groupby('A')['B'].apply(pd.value_counts).count(level=0) 
Out[32]: 
A 
1    4 
2    3 
dtype: int64 

另一种变体:

In [48]: 
 
df.groupby('A')['B'].agg(lambda x: pd.Series.count(x.unique())) 
Out[48]: 
A 
1    4 
2    3 
Name: B, dtype: int64