Patthebug - 10 months ago 102

Python Question

I am using the following code to fill the

`NaN`

`DataFrame`

`df.fillna(0, inplace=True)`

dfMin10 = df

dfMin10['Sum'] = (dfMin10.iloc[1:len(dfMin10.columns)] > 0).sum(1)

dfMin10

When I see the column

`Sum`

`NaN`

`DataFrame (df)`

`NaN`

`NaN`

Any pointers would be highly appreciated.

Answer Source

Are you seeing `NaN`

in the first `sum`

entry? This line:

```
branchConceptsWithScoresMin10['Sum'] = (branchConceptsWithScoresMin10.iloc[1:len(branchConceptsWithScoresMin10.columns)] > 0).sum(1)
```

Should this be:

```
branchConceptsWithScoresMin10['Sum'] = (branchConceptsWithScoresMin10.iloc[0:len(branchConceptsWithScoresMin10.columns)] > 0).sum(1)
```

Note the indexing starting from `0`

.

**Example**:

```
df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
df.fillna(0, inplace=True)
branchConceptsWithScoresMin10 = df
# Your original code
branchConceptsWithScoresMin10['Sum'] = (branchConceptsWithScoresMin10.iloc[1:len(branchConceptsWithScoresMin10.columns)] > 0).sum(1)
# This should return
# a b c d Sum
# x 0 0 0 0 NaN
# y 0 0 0 0 0.0
# z 0 0 0 0 0.0
branchConceptsWithScoresMin10['Sum'] = (branchConceptsWithScoresMin10.iloc[0:] > 0).sum(1)
# There should not be any NaNs here.
```