Is there a function in python that allows me to count the number of non-missing values in an array?

My data:

df.wealth1[df.wealth < 25000] = df.wealth
df.wealth2[df.wealth <50000 & df.wealth > 25000] = df.wealth
df.wealth3[df.wealth < 75000 & df.wealth > 50000] = df.wealth
...

id, income, wealth, wealth1, wealth2, ... wealth9
1, 100000, 20000, 20000, ,...,
2, 60000, 40000, , 40000, ...,
3 70000, 23000, 23000, , ...,
4 80000, 75000, , ,..., 75000
...

My current situation:

income_brackets = [(0, 25000), (25000,50000), (50000,100000)]
source = {'wealth1': [], 'wealth2' :[], .... 'wealth9' : []

for lower, upper in income_brackets:
for key in source:
source[key].append(len(df.query('income > {} and income < {}'.format(lower,upper))[np.logical_not(np.isnan([key]))]))

But this does not work because np.isnan('wealth1') is invalid. it only works with np.isnan(df.wealth1), however I cannot incorporate that into my for loop. I am pretty new to python so perhaps (hopefully) I am missing something obvious.

Any suggestions or question would be great. Thanks! Cheers

有帮助吗?

解决方案

The best way to do this is with the count method of DataFrame objects:

In [18]: data = randn(1000, 3)

In [19]: data
Out[19]:
array([[ 0.1035,  0.9239,  0.3902],
       [ 0.2022, -0.1755, -0.4633],
       [ 0.0595, -1.3779, -1.1187],
       ...,
       [ 1.3931,  0.4087,  2.348 ],
       [ 1.2746, -0.6431,  0.0707],
       [-1.1062,  1.3949,  0.3065]])

In [20]: data[rand(len(data)) > 0.5] = nan

In [21]: data
Out[21]:
array([[ 0.1035,  0.9239,  0.3902],
       [ 0.2022, -0.1755, -0.4633],
       [    nan,     nan,     nan],
       ...,
       [ 1.3931,  0.4087,  2.348 ],
       [ 1.2746, -0.6431,  0.0707],
       [-1.1062,  1.3949,  0.3065]])

In [22]: df = DataFrame(data, columns=list('abc'))

In [23]: df.head()
Out[23]:
        a       b       c
0  0.1035  0.9239  0.3902
1  0.2022 -0.1755 -0.4633
2     NaN     NaN     NaN
3     NaN     NaN     NaN
4     NaN     NaN     NaN

[5 rows x 3 columns]

In [24]: df.count()
Out[24]:
a    498
b    498
c    498
dtype: int64

In [26]: df.notnull().sum()
Out[26]:
a    498
b    498
c    498
dtype: int64

Like many pandas methods, this also works on Series objects:

In [27]: df.a.count()
Out[27]: 498

其他提示

Pandas allows you to access columns in the following way too:

np.isnan(df['wealth1'])

By the way, even if this was not the case, you could still do

np.isnan(getattr(df, 'wealth1'))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top