Using Filter with Count

Using filter with count

I don't think count is what you looking for. Try n() instead:

df %>% 
group_by(StudentID) %>%
filter(n() == 3)

# Source: local data frame [6 x 6]
# Groups: StudentID
#
# StudentID StudentGender Grade TermName ScaleName TestRITScore
# 1 100 M 9 Fall 2010 Language Usage 217
# 2 100 M 10 2011-2012 Language Usage 220
# 3 100 M 9 Fall 2010 Reading 210
# 4 10022 F 8 Fall 2010 Language Usage 232
# 5 10022 F 9 2011-2012 Language Usage 240
# 6 10022 F 8 Fall 2010 Mathematics 242

java 8 stream using filter and count

It's important to check first if the status is not null then only we would be able to use the equals method on status, else we will get NullPointerException. You also don't need to declare count to 0l, count() will return you 0 when no match is found.

List<Employee> employee = new ArrayList<Employee>();
// long count = 0l;

// Status non null and not equals "2" (string)
ling count = employee.stream()
.filter(e -> Objects.nonNull(e.getStatus()) && (!e.getStatus().equals("2")))
.count();

Filtering in count function - Postgresql

You can try to use FILTER clause or condition aggregate function.

SELECT users.id, users.email, users.premium,
COUNT(referrals.referrer) FILTER(WHERE premium = true) as referred
FROM users
LEFT JOIN referrals
ON users.id = referrals.referrer
GROUP BY users.id, users.email, users.premium
ORDER BY referred DESC;

Edit

From you comment you I think you can try to use subquery to do aggregate function to find premium user first, then do OUTER JOIN for user table.

SELECT u.*,
coalesce(referred,0) referred
FROM users u
LEFT JOIN(
SELECT f.referrer,
COUNT(f.id) FILTER(WHERE u1.premium = true) as referred
FROM users u1
JOIN referrals f
ON u1.id = f.id
GROUP BY f.referrer
) t1
ON t1.referrer = u.id

sqlfiddle

Pandas Dataframe : Using the count function to filter data

Another solution without a loop:

s = df.notna().sum(0) == 4     
df = df.loc[:, s]

How to get the updated count on filter selection?

A bit hacky, but you can do this by moving the pipe to a container, and store the value in a local template variable, then you can use the value in the entire container and bind to the length of it. here is a live example.



Related Topics



Leave a reply



Submit