I have a data like below:
JavaScript
x
5
1
Col1 F1 L1 F2 L2 F3 L3
2
A Jon Ro NaN NaN NaN NaN
3
B Koss Lon Pet Gross NaN NaN
4
C Lo NaN NaN NaN NaN NaN
5
I want to get count of non-missing based on F
and L
:
JavaScript
1
5
1
Col1 F1 L1 F2 L2 F3 L3 Cnt
2
A Jon Ro NaN NaN NaN NaN 1
3
B Koss Lon Pet Gross NaN NaN 2
4
C Lo Pho NaN NaN NaN NaN 1
5
I tried below’s code but got wrong result since it considered F
and L
separate instead of based on their suffix:
JavaScript
1
7
1
df["Cnt"] = df[df.filter(regex = "F|L").columns.tolist()].apply(lambda x: x.count(), axis=1)
2
3
Col1 F1 L1 F2 L2 F3 L3 Cnt
4
A Jon Ro NaN NaN NaN NaN 2
5
B Koss Lon Pet Gross NaN NaN 4
6
C Lo Pho NaN NaN NaN NaN 1
7
Any idea?
Advertisement
Answer
JavaScript
1
14
14
1
df['Cnt'] = (
2
df.filter(regex="L|F") # select only L or F columns
3
.groupby(lambda col: col[-1], axis=1) # group the columns by suffix (assuming it's just the last character)
4
.agg(lambda g: g.notna().any(axis=1)) # for each i check if Fi or Li are not NaNs
5
.sum(axis=1) # count the not-NaN groups row-wise (i.e. all the True values)
6
)
7
8
>>> df
9
10
Col1 F1 L1 F2 L2 F3 L3 Cnt
11
0 A Jon Ro NaN NaN NaN NaN 1
12
1 B Koss Lon Pet Gross NaN NaN 2
13
2 C Lo Pho NaN NaN NaN NaN 1
14