简体   繁体   English

通过过滤 Pandas 中的其他 2 列,在第 3 列中获取唯一值

[英]get unique values in a 3rd column by filtering 2 other columns in Pandas

I have a dataframe i would like to filter.我有一个 dataframe 我想过滤。 Consider the below input dataframe.考虑以下输入 dataframe。

a  b  c  
1  1  1
1  0  1
2  2  1
2  2  2

There are 3 columns ( a, b, and c)有 3 列(a、b 和 c)

I would like to get the count of unique values for c, for each unique pair of a and b, for a new d column, which has the count of unique values in c for its a, b pair:我想获取 c 的唯一值计数,对于 a 和 b 的每对唯一值,对于一个新的 d 列,它的 a,b 对具有 c 中的唯一值计数:

a  b  c  d
1  1  1  1
1  0  1  1
1  2  1  2 
1  2  2  2

rows 0, 1 have different a,b column pairs, and so the appended d values for both rows would be 1.第 0、1 行具有不同的 a、b 列对,因此这两行附加的 d 值都为 1。

rows 2 and 3 have shared a, b columns and 2 unique values for that pair, their d values would be 2第 2 行和第 3 行共享 a、b 列和该对的 2 个唯一值,它们的 d 值将为 2

I think you want to use groupby and nunique我想你想使用 groupby 和 nunique

import pandas as pd
data = pd.DataFrame({
    'a':[1,1,2,2],
    'b':[1,0,2,2],
    'c':[1,1,2,3]
})

unique_count = data.groupby(
    ['a','b']
).c.nunique()

data.set_index(['a','b']).assign(
     d = unique_count
).reset_index()

Output: Output:

a   b   c   d
1   1   1   1
1   0   1   1
2   2   2   2
2   2   3   2

Let us try让我们试试

df['cnt'] = df.groupby(['a','b'])['c'].transform('nunique')
df
Out[303]: 
   a  b  c  cnt
0  1  1  1    1
1  1  0  1    1
2  2  2  1    2
3  2  2  2    2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 熊猫按两列分组,并从第三列输出值 - Pandas groupby two columns and output values from 3rd column 如何通过对第三列中的值求和,将前两列中具有相同值的 Pandas Dataframe 的行组合在一起? - How to group together rows of Pandas Dataframe with same values in first 2 columns by summing values in the 3rd column? Pandas:如果来自第三列的字符串值,则根据另一列的值创建列 - Pandas : Create columns based on values of another column if string value from 3rd column Python 比较 2 列并用第 3 列中的值写入第 4 列(熊猫) - Python Compare 2 Columns And Write A 4th Column With Values From 3rd Column (pandas ) 比较来自相同 pandas dataframe 的 2 列的值和基于比较的第 3 列的返回值 - comparing values of 2 columns from same pandas dataframe & returning value of 3rd column based on comparison Python Pandas - 检查两列中的值,对第三列求和 - Python Pandas - check value in two columns, sum the 3rd column 在Pandas DataFrame中比较2列并填充第3列 - Comparing 2 columns in Pandas DataFrame and populating a 3rd column 第 3 列 pandas python 中至少有两列 - Minimum of two columns in a 3rd column pandas python 如何使用其他两列作为轴 plot 第 3 列 - How to plot the 3rd column using the other two columns as axes 根据熊猫中其他列的值添加具有唯一标识符的列 - Add column with unique identifiers based on values from other columns in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM